- Home /
Camera follow players z axis
I need my camera to follow on the z axis only.
I get this error: CameraController.cs(19,27): error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable
Here is my script:
public GameObject player;
private Vector3 offset;
// Use this for initialization
void Start ()
{
offset = transform.position;
//player = transform.position.x;
}
// Update is called once per frame
void LateUpdate ()
{
transform.position.z = player.transform.position.z + offset;
print (player.transform.position.z);
}
}
Part of my camera code is from the Rollaball tutorial. The offset variable represents the cameras current set up position in my scene.
If I rewrite this line 14:
transform.position.z = player.transform.position.z + offset;
as this:
transform.position = player.transform.position + offset;
it gets rid of the error but then the camera follows on all 3 axis.
Thanks for the help.
There are many properties of Unity components you cannot change directly. I have extension methods to counteract this, but the most direct way to avoid it is this:
Vector3 p = player.transform.position;
p.z += offset;
player.transform.position = p;