[Unity] Optimize the singleton mode, the game will not report an error if this script is not added

Now the problem: I wrote a singleton pattern to manage the sound playback in the game, put it in the initial scene and don't destroy it when the scene is loaded.

Every time I test the functionality of other levels, I have to enter from the initial scene, otherwise I will report an error. If I manually add this singleton mode to that scene during the test, there are too many levels and forget to delete it, and an error will be reported here when the game is officially run. It's really annoying.

Saw a solution:

Every time you access this singleton mode, first check whether the script is added to the scene, if not, add it automatically.

code show as below:

  public static AudioManager _instance
    {
        get {
            if (!instance)
            {
                instance = FindObjectOfType(typeof(AudioManager))as AudioManager;
                if (!instance)
                {
                    var obj=new GameObject("AudioManager");
                    obj.AddComponent<BGM_Manager>();
                    instance = obj.AddComponent<AudioManager>();
                    DontDestroyOnLoad(obj);
                }
            }
            
            return instance;
        }
    }

Even for ordinary singleton patterns, there should be protection mechanisms:

public static MainContainer Instance
    {
        get
        {
            if (_instance  == null)
            {
                _instance = new MainContainer();
            }
            
            return _instance as MainContainer;
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325579769&siteId=291194637