- Home /
Question by
shahar_communix · Aug 09, 2021 at 08:02 AM ·
uitransformcanvastransform.positionpositioning
Finding an objects position from one canvas to the other
Hi, I need to position a button in runtime on a canvas at the same position of a different button from a different canvas. I have the both buttons references but I can't seem to solve it. Here is what I tried to do that doesn't work:
//button1 and button2 are not in the same canvas. I want button2 to be on top of button1
Vector3 button1Viewport = camera1.WorldToViewportPoint(button1.transform.position);
Vector3 button2Position = gameObject.GetComponentInParent<Canvas>().worldCamera.ViewportToScreenPoint(button1Viewport);
button2.transform.position = button2Position;
thanks
Comment
Answer by Mrpxl · Aug 09, 2021 at 08:37 AM
Hey! I've got a method for you that does just this:
/// <summary>
/// Converts the anchoredPosition of the first RectTransform to the second RectTransform,
/// taking into consideration offset, anchors and pivot, and returns the new anchoredPosition
/// </summary>
public static Vector2 SwitchToRectTransform(RectTransform from, RectTransform to)
{
Vector2 localPoint;
Vector2 fromPivotDerivedOffset = new Vector2(from.rect.width * 0.5f + from.rect.xMin, from.rect.height * 0.5f + from.rect.yMin);
Vector2 screenP = RectTransformUtility.WorldToScreenPoint(null, from.position);
screenP += fromPivotDerivedOffset;
RectTransformUtility.ScreenPointToLocalPointInRectangle(to, screenP, null, out localPoint);
Vector2 pivotDerivedOffset = new Vector2(to.rect.width * 0.5f + to.rect.xMin, to.rect.height * 0.5f + to.rect.yMin);
return to.anchoredPosition + localPoint - pivotDerivedOffset;
}
In your case, you better want to serialize your buttons as RectTransform and link them in editor. Then you need to call this like so:
button2.anchoredPosition = SwitchToRectTransform(button1, button2);
Hope this helps!
Your answer
Follow this Question
Related Questions
Changing water level 0 Answers
Can't get an actual canvas size 1 Answer
Prefab Instance changing when loading scene in editor 0 Answers
Get position of specific character from Text inside a canvas 0 Answers