In my code I have a variable getting true if a button is pressed, and in another Scripts Update Function an if statement checking wheter the variable is true or not. But in I get a NullReferenceException, in the line, I'm checking the variable. ( I want to make a button where I can start the game, the camera gets in right position and then the player can move, with the camera) The error is: NullReferenceException: Object reference not set to an instance of an object CameraFollow.LateUpdate () (at Assets/Scripts/CameraFollow.cs:33) Why?
public class StartPosition : MonoBehaviour
{
public bool cameraFollow = false;
public void TakeStartPosition()
{
transform.position = new Vector3(1, 1, -1);
cameraFollow = true;
}
}
Other Script for CameraMovement:
public class CameraFollow : MonoBehaviour {
public Transform playerTransform;
public StartPosition followOn;
private Vector3 cameraOffset;
[Range(0.01f, 1.0f)]
public float smoothFactor = 0.5f;
void Start() {
if (followOn.cameraFollow) {
cameraOffset = transform.position - playerTransform.position;
Debug.Log("It must work!!!");
}
}
private void LateUpdate() {
if (followOn.cameraFollow) //This line produces the error
{
Vector3 newPos = playerTransform.position + cameraOffset;
newPos.z = transform.position.z;
transform.position = Vector3.Slerp(transform.position, newPos, smoothFactor);
}
}
}