Search code examples
c#unity-game-engineunity3d-gui

Unity3D - Move UI object to center of screen while maintaining its parenting


I have an UI image that is parented to a RectTransform container, which is parented to a UI panel, which is parented to a Canvas.

I want to be able to move this UI image to the center of the screen (ie. canvas) while leaving the parenting hierarchy. My goal is to animate the UI image from the center to where it is now. Can you please let me know what this code would look like?

enter image description here


Solution

  • What ended up working was changing the parent of the UI Image to the canvas, move the UI image to the middle of the canvas (ie. screen), and reinstate the original UI Image parent relationship. From there, I just needed to animate to the original local position.

    var rectTransform = gameObject.GetComponent<RectTransform>();
    var canvasRendererRectTransform = gameObject.transform.parent.parent.parent.GetComponent<RectTransform>();
    
    rectTransform.SetParent(canvasRendererRectTransform);
    rectTransform.localPosition = Camera.main.ScreenToViewportPoint(Vector3.one * 0.5f);
    rectTransform.SetParent(gridRendererRectTransform);