61 lines
1.0 KiB
C#
61 lines
1.0 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
|
|
{
|
|
private static T _instance;
|
|
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = FindObjectOfType<T>();
|
|
|
|
if (_instance == null)
|
|
{
|
|
GameObject obj = new GameObject();
|
|
obj.name = typeof(T).Name;
|
|
_instance = obj.AddComponent<T>();
|
|
}
|
|
}
|
|
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
protected virtual void Awake()
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = this as T;
|
|
OnLoad();
|
|
DontDestroyOnLoad(gameObject);
|
|
}
|
|
else
|
|
{
|
|
Destroy(gameObject);
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
OnUpdate();
|
|
}
|
|
|
|
|
|
#region 生命周期
|
|
|
|
protected virtual void OnLoad()
|
|
{
|
|
|
|
}
|
|
|
|
protected virtual void OnUpdate()
|
|
{
|
|
|
|
}
|
|
|
|
#endregion
|
|
} |