So I’m making a top-down shooter in 2D mode where the camera has a fixed position. I want to make sure that whenever the player moves a crtain amount of pixels to the left or right, they can’t go beyond that point. So far I’ve been trying (and failing) to achieve this by using this code:
When I build the code in MonoDevelop I get an error reading “Cannot modify the return value of transform.position because it is not a variable.” So far I haven’t been able to find a workaround for this. Any help would be greatly appreciated.
Long story short, because transform.position is a property that returns a value type, a temporary copy is made, and automatically created temporary copies cannot be modified. The solution is to manually create a temporary copy, modify it, then assign it back:
You either use a collider around the level, or do what you already tried, but with the correct logic. It is true that you can’t directly change single values of a transform. However, you can pass it a complete Vector3:
void Update() {
//declare a temporary variable that holds the current position
Vector3 playerPos = transform.position;
//clamp the temporary variable's x value
playerPos.x = Mathf.Clamp(-300,300);
//assign the complete temp variable back to the transform
transform.position = playerPos;
}