unity-game-enginetransformscrollrect

Why is the transform.position.y acting wierd?


it's my first time asking something, I hope I'll do it right.

I am looking to fix the y position of an image in a scroll rect. I have done so on the x axis for another image, and it works perfectly. But for some reason, it doesn't work with the y axis.

Here is the code adapted from what worked on the x axis :

private float startPositionY;

void Start()
{
    startPositionY=transform.position.y;
}
   
void Update()
{
    if (transform.position.y < startPositionY | transform.position.y > startPositionY)
    {
        transform.position = new Vector2(transform.position.x, startPositionY);
    }
}

That doesn't work. When I launch the game, the image disappears immediately. So I tried a few things with DebugLogs :

  1. At the start, startPositionY is equal to the y position. Yes
  2. With the following code, the image is a the right place at the start. :
void Update()
{
    if (transform.position.y == startPositionY)
    {
        transform.position = new Vector2(transform.position.x, startPositionY);
    }
}
  1. But if I add this, suddenly it moves :
void Update()
{
    if(transform.position.y == startPositionY)
    {
        transform.position = new Vector2(transform.position.x, startPositionY);
    }
    else
    {
        transform.position = new Vector2(transform.position.x, startPositionY);
    }
}

All of this before I ever try to scroll, literally on frame 1, before I touch or try to move anything.

I am at a loss. I have tried changing anchor points, but the result is the same. It frustrates me because it works perfectly well for the x axis. What am I missing here ?


Solution

  • First, you shouldn't directly manipulate Transform.position because it conflicts with the layout assistance provided by Canvas. Use RectTransform.

    The following code assumes that the GameObject you want to fix is ​​directly under 'Content'. OnValueChanged is registered to the ScrollRect event of the same name.

    private Vector2 startPosition;
    
    void Start()
    {
        startPosition = ((RectTransform)transform).anchoredPosition;
    }
    
    public void OnValueChanged(Vector2 normalizedPosition)
    {
        var rt = (RectTransform)transform;
        var pos = startPosition;
        pos.y = startPosition.y - ((RectTransform)rt.parent).anchoredPosition.y;
        rt.anchoredPosition = pos;
    }
    

    The apparent position is fixed by moving it in the opposite direction to the 'Content' moved by the ScrollRect.