unity 中实现单例的方法有很多我一般用
工厂代码
public class FactoryManager { #region Class private static Dictionary<Type, object> loadClass = new Dictionary<Type, object>(); private static Dictionary<Type, object> eventloadClass = new Dictionary<Type, object>(); public static T CreatClass<T>() where T : class { Type type = typeof(T); lock (loadClass) { if (loadClass.ContainsKey(type)) return loadClass[type] as T; else { object factory = Activator.CreateInstance(type); loadClass[type] = factory; return factory as T; } } } /// <summary> /// 每次调用后销毁 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T CreatEventClass<T>() where T : class { Type type = typeof(T); lock (eventloadClass) { if (eventloadClass.ContainsKey(type)) return eventloadClass[type] as T; else { object factory = Activator.CreateInstance(type); eventloadClass[type] = factory; return factory as T; } } } public static void ClearEventReference(object t) { Type type = t.GetType(); if (eventloadClass.ContainsKey(type)) eventloadClass.Remove(type); } #endregion #region MonoBehaviour private static Dictionary<Type, MonoBehaviour> loadMonoBehaviour = new Dictionary<Type, MonoBehaviour>(); private static GameObject tempGameObject; public static T CreatSingtonMonoBehaviour<T>() where T : MonoBehaviour { Type type = typeof(T); lock (loadMonoBehaviour) { if (loadMonoBehaviour.ContainsKey(type)) return loadMonoBehaviour[type] as T; else { if (null == tempGameObject) { tempGameObject = new GameObject("Util"); } MonoBehaviour factory = tempGameObject.GetOrAddComment<T>(); loadMonoBehaviour[type] = factory; return factory as T; } } } #endregion }