forked from zxl/LaboratoryProtection
46 lines
1.2 KiB
C#
46 lines
1.2 KiB
C#
using System;
|
|
using Sirenix.OdinInspector;
|
|
using UnityEngine;
|
|
|
|
namespace UnityTest.ZXL
|
|
{
|
|
/// <summary>
|
|
/// 继承MonoBehavior的单例基类
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public abstract class BaseAutoMono<T> : SerializedMonoBehaviour where T : MonoBehaviour
|
|
{
|
|
private static T instance;
|
|
|
|
public static T Instance()
|
|
{
|
|
if (instance == null)
|
|
{
|
|
var findObjectsOfType = GameObject.FindObjectsOfType<T>();
|
|
if (findObjectsOfType.Length > 1)
|
|
{
|
|
throw new Exception($"{typeof(T)}' count is larger than 1");
|
|
}
|
|
|
|
if (findObjectsOfType.Length == 0)
|
|
{
|
|
GameObject go = new GameObject();
|
|
go.name = typeof(T).ToString();
|
|
DontDestroyOnLoad(go);
|
|
instance = go.AddComponent<T>();
|
|
}
|
|
else
|
|
{
|
|
instance = findObjectsOfType[0];
|
|
}
|
|
}
|
|
|
|
return instance;
|
|
}
|
|
|
|
void Awake()
|
|
{
|
|
instance = this.gameObject.GetComponent<T>();
|
|
}
|
|
}
|
|
} |