创建单例基类的方式
方式一:(不继承于MonoBehavior的单例)
////// 不继承任何类的单例基类 /// public abstract class BaseIns where T : class, new() { private readonly static object locaObj = new object(); private static T instance = null; public static T Instance { get { if (instance == null) { lock (locaObj) { if (instance == null) { instance = new T(); } } } return instance; } } }
方式二:(继承于MonoBehavior的单例基类)
using UnityEngine; ////// 继承MonoBehavior的单例基类 /// /// public class BaseAutoMono : MonoBehaviour where T:MonoBehaviour { private static T instance; public static T Instance() { if (instance==null ) { GameObject go = new GameObject(); go.name = typeof(T).ToString(); DontDestroyOnLoad(go); instance = go.AddComponent (); } return instance; } }
以上内容仅作为个人记录,如有不对欢迎指正!