Question

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?

Was it helpful?

Solution

Unity is pretty stupid in this regard, so a bit of a workaround is required. Try this:

Vector3 tmpPos = transform.position;
tmpPos.x = Mathf.Clamp(tmpPos.x, -2.0f, 2.0f);
transform.position = tmpPos;

OTHER TIPS

You cannot access the x value directly, here's a work-around:

transform.position = new Vector3(Mathf.Clamp(transform.position.x, -2.0f, 2.0f), transform.position.y, transform.position.z)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top