FirstComit
This commit is contained in:
35
Assets/Script/SingletonMonoBehavior.cs
Normal file
35
Assets/Script/SingletonMonoBehavior.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using UnityEngine;
|
||||
|
||||
public abstract class SingletonMonoBehavior<T> : MonoBehaviour where T : SingletonMonoBehavior<T>
|
||||
{
|
||||
private static T _instance;
|
||||
|
||||
public static T Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
_instance = FindFirstObjectByType<T>();
|
||||
if (_instance == null)
|
||||
{
|
||||
var go = new GameObject(typeof(T).Name);
|
||||
_instance = go.AddComponent<T>();
|
||||
}
|
||||
}
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void Awake()
|
||||
{
|
||||
if (_instance != null && _instance != this)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
|
||||
_instance = (T)this;
|
||||
DontDestroyOnLoad(gameObject);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user