- Home /
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?
Answer by UnityCoach · Jul 26, 2017 at 10:46 AM
transform.position = new Vector3 (Screen.width * 0.5f, Screen.height * 0.5f, 0);
You may want to test this with different dpi settings.
Answer by junedmmn · Sep 19, 2018 at 10:15 AM
In my case i wanted to Just move an Image inside the Canvas i.e. Slide the Image from Right to Left and place it in middle of Canvas.
desiredPosition += new Vector3(-Screen.width, 0, 0);
This will move from current position to the Desired Position.
To enable smooth slide animation towards the desired position, You can also use the following code inside void Update()
,
player.transform.position = Vector3.MoveTowards(player.transform.position, desiredPosition, 400f * Time.deltaTime);