单例模式基类
public class BaseManager<T> where T : new()
{
private static T instance;
public static T GetInstance()
{
if (instance == null)
instance = new T();
return instance;
}
}
继承自MonoBehaviour的基类
因为继承mono的类不能new本身,该类的调用需要手动添加脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SignletonMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T GetInstance()
{
return instance;
}
protected virtual void Awake()
{
instance = this as T;
}
}
该方法不建议使用,在基础上进行改进。自动添加脚本
继承MonoBehaviour的自动化基类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SignletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T GetInstance()
{
if (instance == null)
{
GameObject obj = new GameObject();
obj.name = typeof(T).ToString();
DontDestroyOnLoad(obj);
instance = obj.AddComponent<T>();
}
return instance;
}
}
|