UnitySingleton
UnitySingleton copied to clipboard
Wouldn't it be nice to "seal" the Awake function?
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() { }