c#及unity單例模板

來源:互聯網
上載者:User

標籤:空間   array   style   abstract   com   bin   not found   oftype   text   

c#:使用泛型實現單例

using System; using System.Collections.Generic; using System.Text; using System.Reflection; /// <summary> /// 1.泛型 /// 2.反射 /// 3.抽象類別 /// 4.命名空間 /// </summary> namespace QFramework {  public abstract class QSingleton<T> where T : QSingleton<T>   {    protected static T instance = null; protected QSingleton() { }       public static T Instance()       {      if (instance == null)       {             // 先擷取所有非public的構造方法             ConstructorInfo[] ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);             // 從ctors中擷取無參的構造方法             ConstructorInfo ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);             if (ctor == null)                 throw new Exception("Non-public ctor() not found!");             // 調用構造方法             instance = ctor.Invoke(null) as T;       }     return instance;     }   } }

unity實現MonoBehaviour 單例,約束GameObject的個數,這個需求,還沒有思路,只好在遊戲運行時判斷有多少個GameObject已經掛上了該指令碼,然後如果個數大於1拋出錯誤即可。在指令碼銷毀時,把靜態執行個體置空。 

using UnityEngine; /// <summary> /// 需要使用Unity生命週期的單例模式 /// </summary> namespace QFramework{   public abstract class QMonoSingleton<T> : MonoBehaviour where T : QMonoSingleton<T>   {       protected static T instance = null;    public static T Instance()     {           if (instance == null)           {              instance = FindObjectOfType<T>();        if (FindObjectsOfType<T>().Length > 1)             {                 QPrint.FrameworkError ("More than 1!");                 return instance;         }             if (instance == null)         {                 string instanceName = typeof(T).Name; QPrint.FrameworkLog ("Instance Name: " + instanceName);                 GameObject instanceGO = GameObject.Find(instanceName);                if (instanceGO == null) instanceGO = new GameObject(instanceName);                 instance = instanceGO.AddComponent<T>();                 DontDestroyOnLoad(instanceGO);                 //保證執行個體不會被釋放                 QPrint.FrameworkLog ("Add New Singleton " + instance.name + " in Game!");             }             else {                 QPrint.FrameworkLog ("Already exist: " + instance.name);             }         }         return instance;     }   protected virtual void OnDestroy() 
  { instance = null;   } }

 

c#及unity單例模板

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.