40 lines
922 B
C#
40 lines
922 B
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
// 创建 monobehaviour 单例
|
|
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
|
|
{
|
|
private static T _instance;
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
if (_instance == null)
|
|
{
|
|
_instance = FindFirstObjectByType<T>();
|
|
if (_instance == null)
|
|
{
|
|
// 创建一个空物体
|
|
GameObject go = new GameObject(typeof(T).Name);
|
|
DontDestroyOnLoad(go);
|
|
// 添加脚本
|
|
_instance = go.AddComponent<T>();
|
|
}
|
|
}
|
|
return _instance;
|
|
}
|
|
}
|
|
|
|
// 初始化
|
|
protected virtual void Awake()
|
|
{
|
|
_instance = this as T;
|
|
Init();
|
|
}
|
|
|
|
public virtual void Init()
|
|
{
|
|
|
|
}
|
|
} |