Can you explain null reference to me and how to avoid it?

I have done a bit of research attempting to go around the error message and do research instead but I have only confused myself further. I do not understand what a null reference exactly is or how to avoid it in a tutorial I have been doing.

using UnityEngine;
using UnityEngine.UI;

public class GameControl : MonoBehaviour {

  private static GameObject whoWinsTextShadow, player1MoveText, player2MoveText;

  private static GameObject player1, player2;

  public static int diceSideThrown = 0;
  public static int player1StartWaypoint = 0;
  public static int player2StartWaypoint = 0;

  public static bool gameOver = false;

//use this for initialization
  void Start () {

    whoWinsTextShadow = GameObject.Find("WhoWinsText");
    player1MoveText = GameObject.Find("Player1MoveText");
    player2MoveText = GameObject.Find("Player2MoveText");

    player1 = GameObject.Find("Player1");
    player2 = GameObject.Find("Player2");

    player1.GetComponent<FollowThePath>().moveAllowed = false;
    player2.GetComponent<FollowThePath>().moveAllowed = false;

    whoWinsTextShadow.gameObject.SetActive(false);
    player1MoveText.gameObject.SetActive(true);
    player2MoveText.gameObject.SetActive(false);
   }


   // Update is called once per frame
   void Update()
  {
    if (player1.GetComponent<FollowThePath>().waypointIndex >
      player1StartWaypoint + diceSideThrown)
    {
      player1.GetComponent<FollowThePath>().moveAllowed = false;
      player1MoveText.gameObject.SetActive(false);
      player2MoveText.gameObject.SetActive(true);
      player1StartWaypoint = player1.GetComponent<FollowThePath>().waypointIndex - 1;
    }

    if (player2.GetComponent<FollowThePath>().waypointIndex >
      player2StartWaypoint + diceSideThrown)
    {
      player2.GetComponent<FollowThePath>().moveAllowed = false;
      player2MoveText.gameObject.SetActive(false);
      player1MoveText.gameObject.SetActive(true);
      player2StartWaypoint = player1.GetComponent<FollowThePath>().waypointIndex - 1;
    }

    if (player1.GetComponent<FollowThePath>().waypointIndex ==
        player1.GetComponent<FollowThePath>().waypoints.Length)

  {
    whoWinsTextShadow.gameObject.SetActive(true);
    whoWinsTextShadow.GetComponent<Text>().text = "Player 1 Wins";
    gameOver = true;
  }

  if (player2.GetComponent<FollowThePath>().waypointIndex ==
      player2.GetComponent<FollowThePath>().waypoints.Length)

{
  whoWinsTextShadow.gameObject.SetActive(true);
  whoWinsTextShadow.GetComponent<Text>().text = "Player 2 Wins";
  gameOver = true;
  }
}

public static void MovePlayer(int playerToMove)
{
    switch (playerToMove) {
        case 1:
            player1.GetComponent<FollowThePath>().moveAllowed = true;
            break;

        case 2:
            player2.GetComponent<FollowThePath>().moveAllowed = true;
            break;
    }
  }
}
using System.Collections;

using UnityEngine;

public class Dice : MonoBehaviour
{
  private Sprite[] diceSides;
  private SpriteRenderer rend;
  private int whosTurn = 1;
  private bool coroutineAllowed = true;

  private void Start (){
    rend = GetComponent<SpriteRenderer>();
    diceSides = Resources.LoadAll<Sprite>("DiceSides/");
    rend.sprite = diceSides[5];
  }

  private void OnMouseDown()
  {
    if (!GameControl.gameOver && coroutineAllowed)
      StartCoroutine("RollTheDice");
  }

  private IEnumerator RollTheDice()
  {
    coroutineAllowed = false;
    int randomDiceSide = 0;
    for (int i = 0; i <= 20; i++)
    {
      randomDiceSide = Random.Range(0, 6);
      rend.sprite = diceSides[randomDiceSide];
      yield return new WaitForSecond(0.05f);
    }

    GameControl.diceSideThrown = randomDiceSide + 1;
    if (whosTurn == 1)
    {
        GameControl.MovePlayer(1);
    } else if (whosTurn == -1)
    {
        GameControl.MovePlayer(2);
    }
    whosTurn *= -1;
    coroutineAllowed = true;
    }

}
using UnityEngine;

public class FollowThePath : MonoBehaviour
{
  private static GameObject waypoint;

  public Transform[] waypoints;

  [SerializeField]
  private float moveSpeed = 1f;

  [HideInInspector]
  public int waypointIndex = 0;

  public bool moveAllowed= false;

  private void Start () {
      transform.position = waypoints[waypointIndex].transform.position;
  }

  private void Update () {
      if (moveAllowed)
        Move();
  }

  private void Move()
  {
    if (waypointIndex <= waypoints.Length - 1)
    {
      transform.position = Vector2.MoveTowards(transform.position,
      waypoints[waypointIndex].transform.position,
      moveSpeed * Time.deltaTime);

      if (transform.position == waypoints[waypointIndex].transform.position)
      {
        waypointIndex +=1;
      }
    }
  }
}

You will NEVER avoid NullReference. You can simply learn how to fix it fast.

Also, if you get a NullReference, you MUST stop and fix it immediately, or else everything else you do will be VERY confusing and broken.

Fortunately, the answer is always the same… ALWAYS. It is the single most common error ever.

It actually doesn’t even matter what you are doing!

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:
- Identify what is null
- Identify why it is null
- Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

1 Like

Null Reference Exceptions are telling you that there is a missing reference where one was expected.

public class Example : MonoBehaviour
{
    public GameObject exampleGO;

    private void Start()
    {
        Debug.Log(exampleGO.GetComponent<Player>().health);
    }
}

In the above example we have a public reference to a game object. In start, we try to get a script called “Player” that is attached to the gameobject, in order to debug log the health value.

However, for this to work you need to drag and drop a gameobject into the available slot in the inspector window. If you don’t a null reference exception will be thrown.

public class Example : MonoBehaviour
{
    private GameObject exampleGO;

    private void Start()
    {
        exampleGO = GameObject.FindWithTag("Player");
        Debug.Log(exampleGO.GetComponent<Player>().health);
    }
}

In the case of where a reference is private, you need to go and find the object in question.

Basically this. (null reference exceptions will always be a part of development due to human error).