- Home /
Using vector2 (transform.position.x, transform.position.y -= 1) error
When I use code like that if (cooldown > 1.5) transform.position.y = new Vector2 (transform.position.x, transform.position.y -= 1);
I get this error "Cannot modify a value type return value of 'UnityEngine.Transform.position'.Consider storing the value in a temporary variable" I know this is a restriction of C# and how it is solved (it actually tells you what to do" but I just don't know how to do it
Helpz plz
Answer by hello1111 · Jun 13, 2014 at 04:54 PM
the x and y components of the variable transform.position may not be modified. you have to replace the entire position variable.
for example, this would also get the same error: transform.position.y = 0.
in your specific code, the problem is you're using "-=" instead of plain old "-". A "-=" 1 means subtract one from A, store the value back in A, and then return the new value of A. A - 1 means just return the value of A minus one.
so just change "-=" to "=" and you should be g2g.
Answer by Landern · Jun 13, 2014 at 04:42 PM
First setting y to a new vector2 is complete nonsense, either way, next time try actually implementing yourself, unity was good enough to give a good exception message...
if (cooldown > 1.5f)
{
Vector3 tempVec3 = transform.position; // Get reference to current position, it is a struct
tempVec3.y -= 1; // Adjust the y axis
transform.position = tempVec3; // set position with adjust y, but keeping x and z the same.
}