Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Unity UI Setting position through scripts between 2 ui elements of different hierarchies.

Discussion in 'UGUI & TextMesh Pro' started by FeastSC2, Jan 7, 2019.

  1. FeastSC2

    FeastSC2

    Joined:
    Sep 30, 2016
    Posts:
    978
    How can I set my UI object @ the same position than another UI object.

    I want to move this red arrow over to the last circle of the Grid Layout.
    The arrow and the circles don't share the same hierarchy of objects, but they share a same canvas.
    Unity_2019-01-07_08-42-16.png

    Using the code below makes me very far off the target.
    I would like to have a method that takes 2 Rect Transforms and puts them on each other so that I have to avoid headaches in the future every time I want to move a UI element to another one. Maybe some of you know how to do this?

    Code (CSharp):
    1.         ArrowSpot.gameObject.SetActive(true);
    2.         var pos = UISkill.GetLastSkillAcquired().RectTransform.position;
    3.         var rectTransform = (RectTransform)ArrowSpot.transform;
    4.         rectTransform.position = pos;
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @FeastSC2

    Sorry if I read your post too quickly, but if you need to place a RectTransform over another, that is on the same Canvas, but has a different parent you can do just this:

    Code (CSharp):
    1. itemRt.position = placementRt.position;
    This works if you have Screen Space or Screen Space Camera Canvas. I usually use Canvas Scaler with "Scale with Screen size" mode, but I guess it could work in other modes too.