I’m writing a script that moves a Canvas Image to a point on the canvas, then back to it’s original position. I only want to move the image on the X axis.
image.rectTransform.localPosition = new Vector2(newLocationX, imageOriginY);
//timer here
//inside the timer
image.rectTransform.localPosition = new Vector2(imageOriginX, imageOriginY);
The image moves on the X axis just fine - it moves to the new position, then back. But the Y axis goes from 441 to 1160.433. I want the Y to stay the same. What’s going on?
The things you THINK you are manipulating are often just properties that feed into a bunch of interim math based on anchoring and scaling and relationships to other objects, and then finally they set the real position.
To do what you want I suggest this approach:
make empty GameObjects where you 1) want the canvas to start, 2) want the canvas to end up
drag references to those RectTransforms into your script
use a tweener or Lerp() to move between the two positions.
That way you can have a chance of getting the anchoring right and getting it to work on all shapes of screens.
Here are some more notes on UI Anchoring, Scaling, CanvasScaler, etc: