Unity is throwing an UnassignedReferenceException during runtime even after reference has been set

Viewed 45

I'm currently working on a script for a basic pause menu. The script is passed two GameObjects through the inspector, each being a different menu, and alternates between setting each object as enabled while setting the other as disabled. The code had worked fine before I moved it to a different script while restructuring my codebase. The script still executes properly, but each time I perform the operation Unity throws an UnassignedReferenceException, telling me to set the reference to the HUD in the inspector. The reference is clearly set and the operation is being performed, but the error is still thrown. I have checked for other instances of the script, and none are present.

Here is the full script in question:

public class GameMenuHandler : MonoBehaviour
{   
    private bool paused;

    [SerializeField] private GameObject HUD;
    [SerializeField] private GameObject pauseMenu;

    void Start()
    {   
        SubscribeMethodsToEvents();
    }
    
    public void RestartLevel()
    {   
        String scene_name = SceneManager.GetActiveScene().name;
        SceneManager.LoadScene(scene_name);
    }

    public void ExitToMainMenu()
    {
        SceneManager.LoadScene("MainMenu");
    }

    public void TogglePauseMenu()
    {
        paused = !paused;
        if (paused)
        {
            HUD.SetActive(false);
            pauseMenu.SetActive(true);
            Time.timeScale = 0f;
        }
        else
        {
            HUD.SetActive(true);
            pauseMenu.SetActive(false);
            Time.timeScale = 1f;
        }
    }

    void SubscribeMethodsToEvents()
    {
        GameEvents.current.onEscapeKeyPress += TogglePauseMenu;
    }

    void UnsubscribeMethodsFromEvents()
    {
        GameEvents.current.onEscapeKeyPress -= TogglePauseMenu;
    }

    void OnDestroy()
    {
        UnsubscribeMethodsFromEvents();
    }
}

Here is the inspector view of the script:

enter image description here

Here is the console after the operation had been performed (successfully) numerous times:

enter image description here

1 Answers

One of the best ways to avoid this error is to set the condition != Null. Try this:

if (HUD) HUD.SetActive(false);
if (HUD) HUD.SetActive(true);
Related