Still getting Null Reference Exception

I’m still getting the NullReferenceException error even after finding the objects in Awake, rather than Start. The game runs fine as far as I can tell, but I don’t like the error. *Edit - the game does not run fine. Now it doesn’t load the wincanvas at the end.

This is the full error:

NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/Scripts/GameManager.cs:19)

Below is the script for GameManager, and line 19 is endScreen.gameObject.SetActive(false); under the Start method.

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

public class GameManager : MonoBehaviour
{
   Quiz quiz;
   EndScreen endScreen;

    void Awake() 
    {        
        quiz = FindObjectOfType<Quiz>();
        endScreen = FindObjectOfType<EndScreen>();
    }
    void Start()
    {
        quiz.gameObject.SetActive(true);
        endScreen.gameObject.SetActive(false);
    }

    
    void Update()
    {
        if(quiz.isComplete){
        quiz.gameObject.SetActive(false);
        endScreen.gameObject.SetActive(true);
        endScreen.ShowFinalScore();
        }
    }

    public void OnReplayLevel(){
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

I think I fixed it, but I don’t understand why. I set the winscreen as active in Unity by checking the box and the whole thing works now.

1 Like

FindObjectOfType does not find inactive objects. If the EndScreen is inactive it won’t find it, causing the NRE when you first try to access it (because it never found it)

2 Likes

love you broooo worked for me

1 Like

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

Privacy & Terms