NullReferenceException: Object reference not set to an instance of an object trying to find GameObj

Hello.

I’m trying to code a simple script that allows me to call menus without coding a script for every menu. For doing that, I’m using a variable that stores the name of the menu that I want to call.

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

public class Menus : MonoBehaviour
{
  public static bool GamePaused = false;
  private string menu = "";

  // Update is called once per frame
  void Update()
  {
    if(Input.GetKeyDown(KeyCode.Escape))
    {
      menu = "PauseMenu";
      checkPause();
    }
    else if(Input.GetKeyDown(KeyCode.LeftShift))
    {
      menu = "SwitchMenu";
      checkPause();
    }
  }

  void checkPause()
  {
    if(GamePaused)
    {
      Resume();
    } else {
      Pause();
    }
  }

  public void Resume()
  {
    GameObject.Find(menu).SetActive(false);
    Time.timeScale = 1f;
    GamePaused = false;
  }

  public void Pause()
  {
    GameObject.Find(menu).SetActive(true);
    Time.timeScale = 0f;
    GamePaused = true;
  }
}

Thank you for reading!

Gameobject.Find will not work on objects which are not active in the scene. You need to store a reference to them. You can either do that in the inspector or in the start/awake methods.

1 Like

I see, that explains a lot. How can I reference the objects in the inspector? On Awake() I would need to hardcode to reference them all?

Put this in your class, outside of any functions:

public GameObject menuObject;

Now go to Unity, wait a moment for it to compile, and look at this object’s inspector. You’ll see a slot named “Menu Object” into which you can drag a reference to your menu, and you can use that directly:

menuObject.SetActive(false);

hmm, got it. Thank you guys :wink: