Search Unity

Question Image.rectTransform Y Adding Random Values

Discussion in 'Editor & General Support' started by unity_1BB79BBCB18502DF89EB, May 1, 2023.

  1. unity_1BB79BBCB18502DF89EB

    unity_1BB79BBCB18502DF89EB

    Joined:
    May 1, 2023
    Posts:
    1
    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.

    Code (CSharp):
    1. image.rectTransform.localPosition = new Vector2(newLocationX, imageOriginY);
    2.  
    3. //timer here
    4.  
    5. //inside the timer
    6. 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?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Manipulating RectTransforms is hairy.

    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:

    https://forum.unity.com/threads/inc...size-between-two-people.1130146/#post-7261747

    https://forum.unity.com/threads/game-ui-button-size-problem.1142650/#post-7337383