Keep getting NullReferenceException

So, I have been following this YouTube series on how to create you’re first game in Unity. I have followed along, redone everything about 4 or 5 times now and yet im still getting the same error. Here is the error.

NullReferenceException: Object reference not set to an instance of an object
GameController.Update () (at Assets/Scripts/GameController.cs:21)

and then heres my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameController : MonoBehaviour {

    public GameObject pipePrefab;
    public Transform pipeSpawn;
    public float minTime;
    public float maxTime;
    public float timer;
    public PlayerController pC;

    // Use this for initialization
    void Start () {
       
    }

    // Update is called once per frame
    void Update() {
        if(timer <= 0 && pC.isStart == true)
        {
            PipeSpawner();
        }
        timer -= Time.deltaTime; // Timer = timer - Time.deltaTime
    }

    void PipeSpawner()
    {
        Instantiate(pipePrefab, pipeSpawn.position, pipeSpawn.rotation);
        timer = Random.Range(minTime, maxTime);
    }
}

The error means something in that line is null and you have to make it not null before the line is processed.

These are all resolved exactly the same way:

  • Look at the line its pointing at
  • Find something that can be null (like your pC variable)
  • Add a Debug.Log(pC) before the line executes
  • If it’s null, then goto 5. If not, goto 1.
  • Put something in that variable so it is no longer null

Thank you :smile: