using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BassManager<T> where T:class,new() { private static T instance; //注意这里我们没有私有化构造函数,其实是不必要的,你知道我们在用单例模式就不会new一个实例了。 public static T Instance { get { if(instance == null) instance = new T(); return instance; } } }
接下来我们写的脚本,只需要继承这个单例模式基类,比如:
1 2 3 4 5 6 7 8 9 10 11
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Test: BassManager<Test> { public void Speak() { Debug.Log("我调用了方法"); } }
public class SingleMono<T> : MonoBehaviour where T : MonoBehaviour { //这个是继承MonoBehaviour的 private static T instance; public static T Instance() { if(instance == null) { GameObject go = new GameObject(typeof(T).ToString()); //过场景不移除 DontDestroyOnLoad(go); instance = go.AddComponent<T>(); } return instance; } }
public class SingletonBase<T> where T : class, new() { private static T instance; protected static readonly object _lock = new object(); public static T GetInstance() { if (instance == null) { lock(_lock) { if (instance == null) { instance = new T(); } } } return instance; } }