Search Unity

Resolved Move UI element to position of other UI element

Discussion in 'UGUI & TextMesh Pro' started by ben4d85, Apr 6, 2023.

  1. ben4d85

    ben4d85

    Joined:
    Dec 26, 2018
    Posts:
    47
    I have one UI element, `newElement`, that I would like to move to the exact position (as it appears on the screen) of a second UI element, `oldElement`. Both elements have entirely different parents and settings (oldElement is part of a GridLayoutGroup), but they are part of the same canvas.

    I have tried the following, to no avail.

    (1) To determine the position of oldElement:

    (A)
    Code (CSharp):
    1. var pos = oldElement.transform.position;
    (B)
    Code (CSharp):
    1. var pos = oldElement.GetComponent<RectTransform>().anchoredPosition;
    (C)
    Code (CSharp):
    1. var pos = oldElement.GetComponent<RectTransform>().localPosition;
    (2) To move newElement to that position:

    (A)
    Code (CSharp):
    1. newElement.transform.DOMove(new Vector3(pos.x,pos.y,0), 1.0f);
    (B)
    Code (CSharp):
    1. newElement.transform.DOLocalMove(new Vector3(pos.x,pos.y,0), 1.0f);
    (C)
    Code (CSharp):
    1. newElement.GetComponent<RectTransform>().DOMove(new Vector3(pos.x,pos.y,0), 1.0f);
    All of these make newElement go to a completely wrong position on the screen.
     
    Last edited: Apr 6, 2023
  2. ben4d85

    ben4d85

    Joined:
    Dec 26, 2018
    Posts:
    47
    Update

    The problem was that the position of `oldElement` was not yet available at the time when I tried to use it, and rather than throwing an error, it used a default position. I got it working by moving it to an IEnumerator with WaitForSeocnds (for now).

    The combination that works for me is:

    Code (CSharp):
    1. var pos = oldElement.transform.position;
    2. newElement.transform.DOMove(new Vector3(pos.x, pos.y, 0), 1.0f);
     
    the_real_ijed likes this.
  3. the_real_ijed

    the_real_ijed

    Joined:
    Dec 6, 2012
    Posts:
    8
    Not all heroes wear capes. Or maybe you do, no idea :D

    Thanks for responding your problem with your fix :)