Clamping is not working. What's the problem?

Here’s my code-
transform.position.x = Mathf.Clamp(transform.position.x, -38, 38);
Is there any problem? I don’t think so. But it saws me an error, whatch the picture downest side, it saws me an error.


Error:Cannot modify the return value of “Transform.position” because it is not a variable.
Is there a way to make it variable and will it solve the problem? Or I would use another way? Please help me as you can!

Assign the vector of the position to a variable, clamp it, and then set the position vector.

 private void Update()
{
     var pos = transform.position;

     pos.x = Mathf.Clamp(pos.x, -38, 38);

     transform.position = pos;
}
1 Like

Thanks you very much, I haven’t tried your code yet, but I understood that it’ll work. When I’ll open Unity I’ll set this code. Hope you’re having a good day. Good luck!