UnitySingleton icon indicating copy to clipboard operation
UnitySingleton copied to clipboard

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

Open neo-mashiro opened this issue 3 years ago • 0 comments

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() { }

neo-mashiro avatar Dec 21 '20 02:12 neo-mashiro