Loading Scene After Returning to Menu Problem

I’ve encounter a problem where after going back to my MainMenu scene after playing the game scene it will then not reload the game properly like it would the first time access it.

Example - Game application loads up on MainMenu, press start to play the game scene, game instruction GUI pops up then click to start, during game you press MainMenu button, MainMenu loads, press start button again to load game scene, game instructions GUI pops up then click to start, game doesn’t start, gives error " the object of type “” has been destroyed but you are still trying to access it. Your script should either check if it’s null or you should not destroy the object."

I’m not understanding why it will not just load exactly the same way as before? The game is procedurally generated when you “click to start” and works perfectly when you first load the scene, the only problem is when going back.

I just want it start over when hitting the MainMenu button as the game did when you first open it up.

-information-
C#

procedurally generated

Game is only made using two scenes

Both Start button and MainMenu but use the “SceneManager.LoadScene(“Name of Scene”)”

So, when you get the error, can you click on it in the console, and then read below if a line number is associated with the error… ?
Then, if so, please post the relevant code for some further assistance.
If no line number is given, for whatever reason… Just post any code that would run right away on the start of a scene (I guess, or just before the other one closes, if you have such a thing).

There’s no automatic way of knowing what’s wrong, eh? :slight_smile:

My console gives me -
MissingReferenceException: The object of type ‘GUIText’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
GUIManager.GameStart () (at Assets/Managers/GUIManager.cs:37)
GameEventManager.TriggerGameStart () (at Assets/Managers/GameEventManager.cs:12)
GUIManager.Update () (at Assets/Managers/GUIManager.cs:31)

My code for GUIManager is-

 void Update()
    {
        if (Input.GetButtonDown("Jump") || Input.GetButtonDown("Fire1"))
        {
            GameEventManager.TriggerGameStart(); //this is line 31
        }
    }

    private void GameStart()
    {
        gameOverText.enabled = false; // This is line 37
        instructionsText.enabled = false;
        runnerText.enabled = false;
        subtitleText.enabled = false;
        scoreText.enabled = false;
        highscoreText.enabled = true;
        realtimescoreText.enabled = true;
        boostuiText.enabled = true;
        boostsText.enabled = true;
        distanceText.enabled = false;
        realtimedistanceText.enabled = true;
        enabled = false;
    }

My code for GameEventManager is

public static class GameEventManager {

    public delegate void GameEvent();
    public static event GameEvent GameStart, GameOver;

    public static void TriggerGameStart()
    {
        if(GameStart != null){
            GameStart(); // This is line 12
        }
    }
    public static void TriggerGameOver()
    {
        if(GameOver != null){
            GameOver();
        }
    }
}

Ah okay, so just GUIText has been destroyed…You assigned that somewhere, maybe in the first time you loaded… and it wasn’t kept around (… was destroyed, & not recreated)?
Just guessing… I have no idea about the rest of your setup, but wherever that variable’s in play, is where I’d look :slight_smile:

I really only need it to load up like it’s a whole new scene like when you first start up the game. That’s what I’m not understanding, why won’t it start new?

oh boy… couple of things i’d check/double check.
The assignment of this GUIText variable.
that I unsubscribed/re-subscribed to the event(s) properly…

"I just want it to work " is obvious… but won’t solve the problem alone, eh? :wink:

Could it be because my GUIManager is static instance?

  private static GUIManager instance;

After reading up on some stuff I didn’t realized that Static are not destroyed and that have to reset these manually.

Looks like you found how to solve it :slight_smile: Cool.

Sorry that I don’t completely understand all this and the “unsubscribed/re-subscribed to the event(s)” is new to me.
I’ve come across some one using this.

void OnDisable(){
ClassName.eventName -= functionName;
}

But I’m still having a hard time with it, is this what you recommend?

Yes.

When you add a listener a static event handler, it will keep firing events at it even after the object’s been destroyed. It simply doesn’t know that the object no longer exists.

So before destroying the object, you need to remove the listener from the static event so it will no longer try to fire events at that object’s listener.

this seems so simple but I can’t figure it out. Thanks for helping.

I keep changing things and added or removing everything I can read on the internet to help out, but nothing seems to help. Every time it seems like, I take care of the problem, it moves to something else. I really feel like it’s that fact of the static class and not fully understand the “unsubscribed/re-subscribed to the event(s) properly”

Can you help me understand or point me in the direction some literature that can explain it better?

I’m listing my error code and the two codes that I feel like are the problem being Static (and changing them from Static didn’t help, just caused more problems with other scripts)

using UnityEngine;
using System.Collections;
using GooglePlayGames;
using UnityEngine.SocialPlatforms;

public class GUIManager : MonoBehaviour {

    public GUIText boostsText, boostuiText, distanceText, realtimedistanceText, gameOverText, instructionsText, runnerText, subtitleText, scoreText, realtimescoreText, highscoreText, highscore;
  

    private static GUIManager instance;

    void Start()
    {
        instance = this;
        GameEventManager.GameStart += GameStart;
        GameEventManager.GameOver += GameOver;
        gameOverText.enabled = false;
        scoreText.enabled = false;
        realtimescoreText.enabled = false;
        boostuiText.enabled = false;
        distanceText.enabled = false;
        realtimescoreText.enabled = false;
        highscoreText.enabled = false;

    }

    void Update()
    {
        if (Input.GetButtonDown("Jump") || Input.GetButtonDown("Fire1"))
        {
            GameEventManager.TriggerGameStart();
        }
    }

    private void GameStart()
    {
        gameOverText.enabled = false;
        instructionsText.enabled = false;
        runnerText.enabled = false;
        subtitleText.enabled = false;
        scoreText.enabled = false;
        highscoreText.enabled = true;
        realtimescoreText.enabled = true;
        boostuiText.enabled = true;
        boostsText.enabled = true;
        distanceText.enabled = false;
        realtimedistanceText.enabled = true;
        enabled = false;
    }

    private void GameOver()
    {
        gameOverText.enabled = true;
        instructionsText.enabled = true;
        scoreText.enabled = true;
        realtimescoreText.enabled = false;
        boostuiText.enabled = false;
        boostsText.enabled = false;
        distanceText.enabled = true;
        realtimedistanceText.enabled = false;
        highscore.enabled = true;
        enabled = true;

    }

    public static void SetBoosts(int boosts)
    {
        instance.boostsText.text = boosts.ToString();
    }

    public static void SetDistance (float distance)
    {
        instance.distanceText.text = distance.ToString("f0");
        instance.realtimedistanceText.text = distance.ToString("f0");
    }

    public static void SetHighscore (float highscore)
    {
        instance.highscore.text = PlayerPrefs.GetString("highscore") + highscore;
    }

}

And

using UnityEngine;
using System.Collections;

public  static class GameEventManager {

    public delegate void GameEvent();
    public static event GameEvent GameStart, GameOver;

    public static void TriggerGameStart()
    {
        if(GameStart != null){
            GameStart();
        }
    }
    public static void TriggerGameOver()
    {
        if(GameOver != null){
            GameOver();
        }
    }
}

Hm, OK I think I see what’s going on now. I’ll do my best to explain.

  1. You start the game, and load your initial scene. I’m assuming that you’re also creating an instance of GUIManager here. This GUIManager instance adds GameStart and GameOver listeners to GameEventManager.

At this point, GameEventManager.GameStart contains one listener: GUIManager.GameStart.

  1. You call TriggerGameStart(). This in turn calls “all” listeners attached (all one of them at this point, lol).

  2. GUIManager.GameStart() runs. Everything is fine. Game loads.

  3. You quit back to the main menu scene. This creates a new instance of GUIManager. This new instance adds its GameStart and GameOver listeners to GameEventManager.

At this point, GameEventManager.GameStart now contains two listeners. The first (nonexistent, see below) GUIManager instance, and the second GUIManager instance. So it tries to run both.

Boom. You get an error.

The reason you got an error is because the first instance of GUIManager no longer exists. GameEventManager doesn’t know about this, and will continue to keep trying to call its listener unless you tell it that it no longer exists.

When you load a new scene, the last scene and its objects are destroyed. This is why the first GUIManager instance no longer exists. Having a static instance won’t prevent this from happening. If you don’t want it destroyed, call DontDestroyOnLoad(). If you do want to destroy it, then you need to remove its listeners from GameEventManager so they won’t get called again.

However, you still need to deal with the fact that each time you load the main menu scene, a new instance of GUIManager is created. This can be dealt with in one of two ways:

  1. Create a new “Startup” scene, and create all your static objects and singletons here. Use DontDestroyOnLoad() to keep these objects alive throughout the application’s lifetime. Then load the main menu scene. Never ever load the startup scene again for as long as the application is running. Just go back to the main menu, and that’s it.

or

  1. In GUIManager.Awake, check if instance is null. If it’s null, set it and you’re good. If instance is not null, that means you’re trying to create a new instance. In this case, just destroy the new instance like so:
           if (instance != null)
           {
               // If a singleton instance already exists, destroy this instance
               Destroy(gameObject);
               return;
           }

Hope that helps!

You explained it very well and I really appreciate it! It seems like a step closer, however depending on how I put it in it either goes back to the same spot as before (click to start) and will either give me the same error or no error at all but won’t go any farther.

I’m just waking up, but I’m thinking to myself that if you keep the Instance as DontDestroyOnLoad, you have to make sure that those GUIText objects are also not destroyed, because you are referencing them.
So, that’s an option.
The other option, is to properly unsubscribe from the events (when you leave the scene, for example), and in that case, you wouldn’t have to keep things from destroying and you could overwrite the old static instance variable. and re-assign new events when the scene loads (and your variables would be okay because they’d be “fresh”)
Removing subscriber(s):

void OnDisable() {
   GameEventManager.GameStart -= GameStart;
   GameEventManager.GameOver -= GameOver;
}

It just keeps going around in circles, If I add DontDestroyOnLoad to the GUIText it then moves on to Character and then that cause more problem. I went through and added the OnDisable and cause problems with the gamescene starting over again or properly ending.

I’m going to have to give up on this and find a other way or just quit and not put out the Update to my game and apologize to everyone. I’ve already spent several days on this one simple problem and I feel like a compete failure. I just need to move along or give up.