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

Hi, I’m kind of new with Unity and I’m having difficulties with a single option when creating a GUI menu.
What I want to do, is that when the pause menu appears, the player and the enemies stop moving. So i wrote this in my SettingPopup class :

 public GameObject menu;
    private RayShooter cursorMenu;
    void Start (){
    cursorMenu = menu.GetComponent<RayShooter> ();
}

public void Open() {
		gameObject.SetActive (true);
		cursorMenu.openMenu = true;
		Debug.Log ("OK3");
		Time.timeScale = 0f;
}
public void Close() {
		gameObject.SetActive (false);
		cursorMenu.openMenu = false;
		Time.timeScale = 1f;
	}
}

And in my RayShooter class :

public bool openMenu = false;

void Update() {
		if (Input.GetKeyDown (KeyCode.T) && (!openMenu)) {
			ToggleCursorLock ();
		} 

shortly, ToggleCursorLock (); is starting a fonction stoping the player to move.

After testing everything out, when I enter my menu, the player still is available to move freely, same for the enemies. But, if I close the menu and start it back, everything’s working exactly like I want. It’s just the first time I got nothing at all. In the console, the first time, when it tries to read the cursorMenu.openMenu = false;, it stops running and I don’t get the Debug.Log (wich appears the other times i open the menu). When I start the game I receive this error :

NullReferenceException: Object reference not set to an instance of an object
( The line cursorMenu.openMenu = false;)
SettingsPopup.Close () (at Assets/Scripts/SettingsPopup.cs:47)
(SettingsPopup.Close (); to start the game having the menu closed)
UiController.Start () (at Assets/Scripts/UiController.cs:25)
When I open the menu (The 1st time only) I get a similar error with the line
SettingsPopup.Open () (at Assets/Scripts/SettingsPopup.cs:40) and long long error lines that I don’t get.

I don’t understand what did wrong, what I need to do, and why it’s working all the time except the first time I’m opening the menu. Help will be really appreciated :slight_smile:

Thanks a lot

Joey

I don’t actually see the lines that generated the error you posted, in the code you posted, like “SettingsPopup.Close ()”

I can still point out that, this error is usually due to an object not being initialzized, in particular, instantiated.
I see this line in your Start function:

cursorMenu = menu.GetComponent<RayShooter> ();

However, due to the error, I suspect this is not being called initially, so cursorMenu is not instantiated before being used. I’m not quite sure why it’s not being called though. Perhaps try using “Awake” instead of “Start”? That’s usually where I would do initialization of that kind.