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 :
void Update()
{
if (transform.position.y == startPositionY)
{
transform.position = new Vector2(transform.position.x, startPositionY);
}
}
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 ?
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.