Skip to content

Latest commit

 

History

History
65 lines (57 loc) · 1.34 KB

singleton.md

File metadata and controls

65 lines (57 loc) · 1.34 KB
title category layout tags prism_languages
Singleton
Design Patterns
2017/sheet
Featured
csharp

Singleton

// Define singleton class
public class SingletonClass: MonoBehaviour {
    private static SomeClass instance;

    public static SomeClass Instance { get { return instance; } }

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

// Use it in another class
public class AnotherClass: MonoBehaviour {
    public Singleton instance;

    private void Awake() {
       instance = Singleton.Instance;
    }
}

Helper class

public class Singleton<T> : MonoBehaviour where T : Component {
    private static T _instance;
    public static T Instnace {
        get {
            if (_instance == null) {
                _instance = FindObjectOfType<T>();
                if (_instance == null) {
                    GameObject obj = new GameObject();
                    _instance = obj.AddComponent<T>();
                }
            }
            return _instance;
        }
    }

    protected virtual void Awake() {
        _instance = this as T;
    }
}

Usage example

public class GameManager : Singleton<GameManager> {
    void Start() { }
    void Update() { }
}