1
0
Fork 0
LaboratoryProtection/Assets/UnityTest/ZXL/Scripts/BaseAutoMono.cs

46 lines
1.2 KiB
C#
Raw Normal View History

2023-09-14 15:36:17 +08:00
using System;
using Sirenix.OdinInspector;
2023-09-13 15:04:19 +08:00
using UnityEngine;
namespace UnityTest.ZXL
{
/// <summary>
/// 继承MonoBehavior的单例基类
/// </summary>
/// <typeparam name="T"></typeparam>
2023-09-14 15:36:17 +08:00
public abstract class BaseAutoMono<T> : SerializedMonoBehaviour where T : MonoBehaviour
2023-09-13 15:04:19 +08:00
{
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];
}
2023-09-13 15:04:19 +08:00
}
return instance;
}
2023-09-14 15:36:17 +08:00
void Awake()
{
instance = this.gameObject.GetComponent<T>();
}
2023-09-13 15:04:19 +08:00
}
}