Move UI element to position of other UI element

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)

var pos = oldElement.transform.position;

(B)

var pos = oldElement.GetComponent<RectTransform>().anchoredPosition;

(C)

var pos = oldElement.GetComponent<RectTransform>().localPosition;

(2) To move newElement to that position:

(A)

newElement.transform.DOMove(new Vector3(pos.x,pos.y,0), 1.0f);

(B)

newElement.transform.DOLocalMove(new Vector3(pos.x,pos.y,0), 1.0f);

(C)

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.

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:

var pos = oldElement.transform.position;
newElement.transform.DOMove(new Vector3(pos.x, pos.y, 0), 1.0f);
1 Like

Not all heroes wear capes. Or maybe you do, no idea :smile:

Thanks for responding your problem with your fix :slight_smile: