c1_unity/Assets/Scripts/Common/MonoSingleton.cs
2023-04-03 11:04:31 +08:00

66 lines
1.7 KiB
C#

using UnityEngine;
using System.Collections;
namespace BF
{
public class MonoSingleton<T> : MonoBehaviour where T : Component
{
bool inited;
static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType(typeof(T)) as T;
if (instance == null)
{
var obj = new GameObject();
#if UNITY_EDITOR
obj.hideFlags = HideFlags.DontSave;
#else
obj.hideFlags = HideFlags.HideAndDontSave;
#endif
obj.name = typeof(T).ToString();
instance = (T)obj.AddComponent(typeof(T));
}
else
{
var ms = instance as MonoSingleton<T>;
ms.Init();
}
}
return instance;
}
}
protected virtual void Init()
{
if (inited)
{
return;
}
inited = true;
}
protected virtual void Awake()
{
DontDestroyOnLoad(gameObject);
if (instance == null)
{
#if UNITY_EDITOR
gameObject.hideFlags = HideFlags.DontSave;
#else
gameObject.hideFlags = HideFlags.HideAndDontSave;
#endif
gameObject.name = typeof(T).ToString();
instance = this as T;
var ms = instance as MonoSingleton<T>;
ms.Init();
}
}
}
}