Đỗ Trọng Khoa
Đỗ Trọng Khoa

Reputation: 79

Singleton Design Pattern question Unity3D

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:

Upvotes: 1

Views: 183

Answers (1)

Cristiano Schiaffella
Cristiano Schiaffella

Reputation: 619

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

Upvotes: 2

Related Questions