UnityCommunity / UnitySingleton

The best way to implement singleton pattern in Unity.
https://en.wikipedia.org/wiki/Singleton_pattern
MIT License
458 stars 61 forks source link

Wouldn't it be nice to "seal" the Awake function? #4

Closed neo-mashiro closed 11 months ago

neo-mashiro commented 3 years ago
protected virtual void Awake() {
    if (_instance == null) {
        _instance = this as T;
        DontDestroyOnLoad(gameObject);
    }
    else {
        Destroy(gameObject);
    }
}

The Awake() function is the key part to make the derived singleton class persistent across scenes and prevent duplicates, but it is marked as protected virtual, so that one could accidentally override it but forgot to add the base.Awake() call, which would then break things apart, and it's hard to debug...

I think maybe we can improve by doing sth like this?

private void Awake() {
    if (_instance == null) {
        _instance = this as T;
        DontDestroyOnLoad(gameObject);
        Initialize();
    }
    else {
        Destroy(gameObject);
    }
}

protected virtual void Initialize() { }
hasanbayatme commented 11 months ago

Yeah your point is completely valid, I'll add this coupled with #2, let me know if you have any other suggestions!

hasanbayatme commented 11 months ago

Added Init method that is called on creation of the instance or reusing the instance from existing object in the scene from Awake method at e902a9f