It seems like I cannot assign members (x,y,z) of the gameObject.transform.position property using C#, it gives this exception:
error CS1612: Cannot modify the return value of `UnityEngine.Transform.position' because it is not a variable
However, the Unity docs have an example for Mathf.Clamp() method that does exactly what I need:
transform.position.x = Mathf.Clamp(transform.position.x, 0f, 10f);
Is it a known issue, or am I missing something?
I’d like to perform the direct assignment to clamp the position and avoid creating a new Vector3 object in every Update().
Thanks!
Vector3 is a struct, which is passed by value and not by reference. In C# you must do:
Vector3 position = transform.position;
position.x = Mathf.Clamp(position.x, 0f, 10f);
transform.position = position;
The documentation uses JavaScript, will allows this through compiler magic.
Structs are created on the stack and not the heap, which doesn’t allocate anything. Don’t worry about performance.
Thank you, Matthew
I did not know Vector3 is a struct, that explains it.
Alternately, you could do this:
transform.position = new Vector3(Mathf.Clamp(position.x, 0f, 10f), transform.position.y, transform.position.z);
This was helpful for me, but I was able to clean it up a bit:
Vector3 position = transform.position;
position.x = 2.0f;
transform.position = position;
I’ve found that extension functions can be useful if you end up doing this a lot.
JScotty
7
Wow thank you!! haha i hace tried to figure this out for hours! haha and it was pretty easy xD
But thanks!
i can go further now.
My code:
Thanks 
Justin Bieshaar - Game Development Student ,Media College Amsterdam