Home > OS >  Singleton Design Pattern question Unity3D
Singleton Design Pattern question Unity3D

Time:08-10

I have some codes below

  [SerializeField] int playerLives = 3;

void Awake()
{
    int numGameSessions = FindObjectsOfType<GameSession>().Length;
    if(numGameSessions > 1)
    {
        Destroy(gameObject);
    }
    else
    {
        DontDestroyOnLoad(gameObject);
    }
}

Explain situation:

  • First I have one obj in my hierarchy like this enter image description here and then the Don't Destroy On Load appears, and the game works normally.
  • But when I put 3 Game Session into my Scene, all disappear and the Don't Destroy On Load doesn't appear, why does this happen?

CodePudding user response:

In your example, when you have 3 items when the first Awake starts all the 3 Game Sessions are already attached to the scene, so it will destroy all GameSession objects. This is not the right way to do Singleton pattern in Unity. A better approach would be:

using UnityEngine;
        
public class Singleton : MonoBehaviour {
    private static Singleton instance;
    public Singleton Instance { get { return instance; } }

    void Awake() {
        if (instance == null) {
            instance = this;
            DontDestroyOnLoad(this.gameObject);
        } else {
            Destroy(this);
        }
    }
}

you can then get your instance by calling Singleton.Instance

  • Related