- Home /
Clamp X position of object
Here is my code in unity 3d
moveDirection = Vector3.forward + new Vector3(Input.acceleration.x * 0.3f, 0, 0);
// transform.position.x = Mathf.Clamp(transform.position.x, -2.0f, 2.0f);
transform.Translate(moveDirection * Time.deltaTime *9);
A object moving forward. I want to clamp its x position.
transform.position.x = Mathf.Clamp(transform.position.x, -2.0f, 2.0f);
which gives me
error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position. Consider storing the value in a temporary variable
How can i clamp my object?
Answer by whydoidoit · Apr 16, 2013 at 09:13 AM
In C# you can't change the value of a member of a struct returned from a property. transform.position is a property so changing x would change it in the copy returned which is then discarded.
Do what the error message tells you to do:
var pos = transform.position;
pos.x = Mathf.Clamp(transform.position.x, -2.0f, 2.0f);
transform.position = pos;
I am totally blown away right now. When I read on the syntax difference between uJS and C#, the declaration for variable in each languages are var i : int
or var i
and int i
respectively, I made the assumption that var
will not work in C#.
Just learnt something new today.
I'm guessing the choice to use var is in case position gets changed from a Vector3 to another variable type that includes a field/property for x?
Your answer
Follow this Question
Related Questions
Middle of screen vector 3? 2 Answers
A node in a childnode? 1 Answer
Finding covered distance of a gameobject 1 Answer
object transform and clamp in local direction 0 Answers
Transform continue direction 0 Answers