Null reference exception

I’ve been trying to figure out how to remedy null reference exemptions for Laser Defender.
When I click start from the start screen and go into the game I get a Null reference exception that there is no instance for Level.LoadGame() (even though it loads the game just fine)

If i start the editor from the Game Over screen I get a null reference exception for ScoreDisplay.Update()

I know that its not really effecting anything but I’m curious how I would tighten my code up so that I don’t receive errors like this. I’ve tried using difference if statements to have it ignore the missing object but that didn’t work. Or is this normal and I’m forced to have to look at the error’s in error log even though they’re not effecting anything?

1 Like

I have encountered the same problem in almost all projects.
What I have figured out so far is: if it is a red message, then something isn’t linked in the inspector and it needs to be fixed (the game isn’t playing anyways and unity won’t let you go on).
If the error message is yellow - as it happens, e.g., when I have a situation where I link an object in some cases and in others not - the game works fine.
I do believe this could be solved via different coding, not sure though if it is worth it or if it even can be done always.
The Unity Manual is not really helpful in this case, as the game is working just fine despite the “error” and one knows exactly where it occurs.
So I subscribe Luc’s question - do we simply accept the annoying message or is there a brilliant solution to get rid of the Null reference exception (yellow error message)?

So i did some more research and found that using a null check in Awake method actually squashes the issue. Of the exception reoccurring, but the issue still occurs once. The rest of the functionality is there though. This is what my code looked like.
public class ScoreDisplay : MonoBehaviour
{
Text scoreText;

GameSession gameSession;



// Start is called before the first frame update
void Start()
{
    scoreText = GetComponent<Text>();
    gameSession = FindObjectOfType<GameSession>();
}

// Update is called once per frame
void Update()
{
    scoreText.text = gameSession.GetScore().ToString();

}

private void Awake()
{
    

    if (gameSession != null && !gameSession.Equals(null))
    {
        Instantiate(gameSession, transform.position, Quaternion.identity);
        scoreText = GetComponent<Text>();
        scoreText.text = gameSession.GetScore().ToString();
    }
    else
    {
        gameSession = FindObjectOfType<GameSession>();
        scoreText = GetComponent<Text>();
        scoreText.text = gameSession.GetScore().ToString();

    }



}

Hi Patrick,

Is the score text a child of the Game Session game object? Is the GameSession class a “singleton”? If so, check if your “singleton” calls gameObject.SetActive(false); in the same if-block where Destroy(gameObject); gets called. If it does not, add that line.


See also:

Thanks for the reply Nina,

I added that line of code where you added so it looks like this

private void SetUpSingleton()
    {

        int numberGameSessions = FindObjectsOfType<GameSession>().Length;

        if(numberGameSessions > 1)
        {
            Destroy(gameObject);
            gameObject.SetActive(true);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }

      
    }

I wasn’t sure if I was supposed to set the statement to true, but I guessed that I was. I commented out the code I had implemented previously to scoredisplay.cs. I’m getting thrown the exception again multiple times (because of the function being placed in update) saying that ScoreDisplay.Update() is not set to an instance of an object. Should I comment back in what I had applied to ScoreDisplay.cs?

Oh noes! I forgot the most important part. It must be gameObject.SetActive(false);. The FindObjectOfType method can find only active objects. Since the Destroy does not destroy immediately, we disable our current game object so the method cannot find the “destroyed” game object.

(I’ve just added the missing false to my previous answer.)

That seems to have worked. Thank you! :smile: I’m also getting thrown an exception for Level.LoadGame().

When clicking on it, I have

public void LoadGame()
    {

        SceneManager.LoadScene("Game");

        FindObjectOfType<GameSession>().ResetGame();
        

    }

And in my ResetGame() its just Destroy(gameObject). I get the exception when launching from the Start screen. I tried some different things with it to see if they’d work but didn’t have any luck. Does gameObject.SetActive() only work in the instance of singletons and finding game objects?

Is there a GameSession object in your Start scene? If there isn’t any, you get a NullReferenceException.

Thank you @Nina I think I understand now.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms