I want to create a Cube, that moves 1 to x-position if i press “w” in C#
So I wrote:
…
void Update ()
{
if (Input.GetKeyDown(KeyCode.W))
{
gameObject.transform.position.x += 1;
}
}
…
but then there ist the warning : “Assets/SnakeSteuerung.cs(18,46): error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position’. Consider storing the value in a temporary variable”
can you pleae help me ? Sorry for my bad English…
1 Answer
1
- transform.position is a Vector3.
- Vector3 is a struct
- A struct is passed by value (it is copied, you don’t have a reference to the original)
- position is a property of transform (not just a variable) so it returns a copy of the value not the actual position itself
- When you do gameObject.transform.position you now have a copy of the position
- If you set x then you set it on the copy that is immediately discarded
- The compiler won’t let you do that, because it can’t be wise
- So you need to take a copy of the position, change the x in the copy and set the whole position back to the updated copy
Also - there is never any need to do gameObject.transform - you will always be able to get it from .transform
So either:
var pos = transform.position;
pos.x += 1;
transform.position = pos;
Or work with vectors which you can multiply to get the right value
transform.position += Vector3.right * 1; //Obviously don't x1 if you really want 1 :)
yet another super-cool nickname !
– Fattie