Pull up singleton behaviour.
This commit is contained in:
25
Assets/Cryville/Common/Unity/SingletonBehaviour.cs
Normal file
25
Assets/Cryville/Common/Unity/SingletonBehaviour.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Cryville.Common.Unity {
|
||||
public abstract class SingletonBehaviour<TSelf> : MonoBehaviour where TSelf : SingletonBehaviour<TSelf> {
|
||||
static TSelf s_instance;
|
||||
public static TSelf Instance {
|
||||
get {
|
||||
return s_instance;
|
||||
}
|
||||
}
|
||||
bool _validInstance;
|
||||
protected virtual void Awake() {
|
||||
if (s_instance != null) {
|
||||
Debug.LogErrorFormat("Duplicate singleton behaviour {0}", typeof(TSelf));
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
s_instance = (TSelf)this;
|
||||
_validInstance = true;
|
||||
}
|
||||
protected virtual void OnDestroy() {
|
||||
if (_validInstance) s_instance = null;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user