Search code examples
c#unity-game-engineunity-ui

How can I modify the height of a rect transform, while making it appear as it is the same position as before in unity?


So I would like to change the height of a rect transform through code, but I want it to appear as if it is at the same position. The reason for this is because I have a mask that I want to slowly increase in size but only upwards (like, it first reveals the bottom and then continues up), but if I do that normally and just changing the sizeDelta it looks like it is moving, but the Y coordinate stays the same. So what I need to do is to find a way to change the Y position in a way that makes it look like the object is standing still.


Solution

  • Answering my own question as I found out how to do it. What I did was to store the Y position at the start and the height. Then every frame i just ran this code

    rect.localPosition = new Vector3(rect.localPosition.x, startPosY - ((startHeight - rect.sizeDelta.y) * 0.5f), rect.localPosition.z);
    

    I found out that when changing the height by a positive value the y position decreased by half of that. (this also works if you change the height by a negative value, but then the y position would increase instead of decrease).

    Hope this might help someone in the future :)