NullReferenceException: Object reference not set to an instance of an object

Hey guys,

This one’s really testing my sanity, so I’m hoping you can help. I’m getting a null error from one of my scripts when I call a variable from another script, and I can’t figure out what the reason is.

Now I have a script called cs_GM that is attached to an empty called GameManager, which holds static references to several scripts in my game. I have another script called cs_UIManager which displays all of my UI, which is attached to the UI canvas. And the script I’m having the problem with, called cs_LivesDisplay, is also attached to the canvas that cs_UIManager is attached to. In it, it calls a variable called currentLives from a script called cs_LivesManager, which is attached to the GameManager object.

The problem I’m having is that when it calls that variable, it returns null, and I can’t figure out why it’s returning null. If I copy/paste the line that calls the variable to cs_UIManager, it works fine from there.

I’m sure I’m missing something simple. Can someone please point it out to me?

Here are the relevant scripts. Sorry to leave so many, but I don’t want to leave out something that might be the problem. Thanks.

cs_GM

using UnityEngine;
using System.Collections;

public class cs_GM : MonoBehaviour {

	public static GameObject Player;

    public static cs_PlayerMove ref_cs_PlayerMove;
	public static cs_PlayerDamage ref_cs_PlayerDamage;
	public static cs_PlayerInventory ref_cs_PlayerInventory;
	
	public static cs_SpawnManager ref_cs_SpawnManager;
    
    public static cs_UIManager ref_cs_UIManager;
    public static cs_ItemHUD ref_cs_ItemHUD;

    public static cs_TimeManager ref_cs_TimeManager;

    public static cs_ScoreManager ref_cs_ScoreManager;

    public static cs_PlayerRespawn ref_cs_PlayerRespawn;

    public static cs_CameraFollow2D ref_cs_CameraFollow2D;

    public static cs_LivesManager ref_cs_LivesManager;

    public static cs_ReachExit ref_cs_ReachExit;

    public static debugTest ref_debugTest;

}

cs_UIManager

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class cs_UIManager : MonoBehaviour {

	public Text healthAmount;
    public Image healthBar;
    public Image timeBar;
    public Text enemiesAmount;
    public Text scoreAmount;
    public Text timeElapsedAmount;
    public Text timeLeftAmount;
    public Text livesAmount;
    public Text bombsAmount;


    void Start ()
    {
        cs_GM.ref_cs_UIManager = this;     // allows this static script to be accessed by the other scripts

        DisplayUI();
    }
	
	
	void Update ()
    {
        DisplayUI();
    }

    void DisplayUI()
    {
        healthAmount.text = cs_GM.ref_cs_PlayerDamage.playerHealth.ToString("0");
        healthBar.fillAmount = cs_GM.ref_cs_PlayerDamage.playerHealth * 0.01f;
        timeBar.fillAmount = cs_GM.ref_cs_TimeManager.timeLeft * 0.05f;
        bombsAmount.text = cs_GM.ref_cs_PlayerInventory.hasBomb.ToString("0");
        timeElapsedAmount.text = cs_GM.ref_cs_TimeManager.timeElapsed.ToString("000");
        timeLeftAmount.text = cs_GM.ref_cs_TimeManager.timeLeft.ToString("00");
        scoreAmount.text = cs_GM.ref_cs_ScoreManager.score.ToString("000");
        livesAmount.text = cs_GM.ref_cs_LivesManager.currentLives.ToString("0");

        Debug.Log(cs_GM.ref_cs_LivesManager.currentLives);  // **** DOES NOT RETURN NULL ****

    }
}

cs_LivesDisplay, in which I am getting the error

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

public class cs_LivesDisplay : MonoBehaviour 
{

    void Start () 
	{
        Debug.Log(cs_GM.ref_cs_LivesManager.currentLives);  // ****RETURNS NULL****
    }
	
}

cs_LivesManager

using UnityEngine;
using System.Collections;

public class cs_LivesManager : MonoBehaviour 
{
    public int currentLives = 3;            // the number of lives the player has

	void Start ()
	{
        cs_GM.ref_cs_LivesManager = this;     // allows this static script to be accessed by the other scripts
    }

	void Update ()
	{
        if(currentLives == 0)           // if player has no more lives
        {
            Debug.Log("Game Over");     // call Game Over function here
        }
	}

    public void GiveLife()
    {
        currentLives++;  // increments lifeCounter by +1
        
    }

    public void TakeLife()
    {
        currentLives--;  // increments lifeCounter by -1
        
    }
}

I think I see your problem. The Start events for each script component in the scene are called sequentially when the scene loads, and if the Start event in cs_LivesDisplay is called before the Start event in cs_LivesManager, then it’ll try to access cs_GM.ref_cs_LivesManager before it’s been initialized, giving you a null reference error.

There’s a few ways to fix this:

  1. You could have cs_LivesManager initialize cs_GM.ref_cs_LivesManager in the Awake event instead of Start. For objects that are part of the scene when the scene starts, Awake and Start are functionally identical, except all the Awake events are called first, so any code in an Awake event is guaranteed to run before any code in a Start event (excluding objects instantiated during runtime).

  2. You can force scripts to execute in a specific order in Edit → Project Settings → Script Execution Order. The manual describes this feature as affecting Awake, OnEnable, and Update; I believe it affects Start too, but I’m not certain.

  3. You can change all the fields in your game manager script from static fields to instance fields and link your scripts to them in the inspector instead of in Start events.

This may not resolve your issue, but restarting Unity seemed to fix it for me.

NullReferenceException: Object reference not set to an instance of an object is a common error. it means that Somehwhere in you code you are trying to use a game object variable before it is assigned. to find where your error is check to see if your gameobject variables are “null” before you try to access its scrips or components.

if (gameobjectvariable==null){print("this is where my problem is"):}