单例模式,需要用到单例的继承这个基类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 单例基类,需要单例的继承这个
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseManager<T>where T:new()
{
private static T instance;
public static T GetInstance()
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
/// <summary>
/// 使用monobehavior 的单例,只需要继承,使用时直接调用 GetInstance()方法即可,无需挂载脚本
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonMono<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();
instance = obj.AddComponent<T>();
}
return instance;
}
}
一个继承mono一个不继承mono。
GetInstance | 获取单例对象 |
测试:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingleTest : SingletonMono<SingleTest>
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}