-3

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);

        }

    }
}
derHugo
  • 49,310
  • 9
  • 37
  • 73
Thboss
  • 15
  • 2

2 Answers2

1

You either forgot to assign followOn a value, which is unlikely since yours Start method doesn't produce an error, or you deleted the StartPosition component at some point before executing LateUpdate.

The question needs more information to be answered conclusively though.

Renge
  • 438
  • 3
  • 14
0

The probably didn't assign a value to your Startposition type variable. The computer doen't know what you mean, so it puts the value to null. What creates the error.

Thboss
  • 15
  • 2