I am trying to script so when the object reaches certain height, his height is equal to that height, so he won’t go higher.
I have been using this but it says “Cannot modify the return value of ‘Transform.position’ because it’s not a variable”
if (transform.position.y > highestPosition)
transform.position.y = highestPosition;
1 Like
The reasons you can’t do this are somewhat complicated. It has to do with how C# deals with struct
properties. Transform.position
is a property and when you access it it’s returning a copy of the position since it’s a struct. So modifying any of the fields in the struct ( y
in your case) wouldn’t have any effect since you’d be modifying a copy. Rather than silently not do anything the compiler gives you an error.
The proper way to handle this is to set the position property to a new Vector3…
Vector3 p = transform.position;
if (p.y > highestPosition)
{
p.y = highestPosition;
transform.position = p; // you can set the position as a whole, just not individual fields
}
Unity is telling you it can’t directly modify the ‘transform.position.y’ value; I don’t know why Unity doesn’t let you do this, but this is how you fix it:
private float y;
void Start()
{
y = transform.position.y;
}
void Update()
{
if(y > highestPosition)
y = highestPosition;
}
Usually it tells you to store it in a variable, which I did here. If this didn’t help feel free to ask more questions!
I think I solved it… this line changes the y position without changing x and z.
transform.position = new Vector3(transform.position.x, [insert y here] , transform.position.z);