基於unity的單例設計模式寫法

來源:互聯網
上載者:User

標籤:基於   color   turn   span   指令碼   單例設計   type   games   void   

設計模式有23中,都是為瞭解藕設計的。就先拿單例設計模式說說把。因為平常最起碼你也得用到單例設計先弄一個泛型的單例模板代碼如下:

 1 //泛型的單例設計模式。項目中用的多 2 public class GameController<T> : MonoBehaviour where T :GameController<T> { 3     private static T _instance; 4     public static T Instance 5     { 6         get 7         { 8             if (_instance == null) 9             {10                 _instance = FindObjectOfType<T>();11             }12             return _instance;13         }14     }15 }

再寫一個指令碼把函數繼承自這個單例指令碼就可以了

 1 public class GameStart : GameController<GameStart> { 2  3     public void Show(GameObject go) 4     { 5         go.SetActive(true); 6  7     } 8     void Awake() 9     {10        11         Debug.Log(11);12     }13 }

然後我這個指令碼因為繼承了泛型單例,它就是一個單例了。然後我在弄個指令碼就可以調用了。

1 public class XXX : MonoBehaviour {2 3     public GameObject prefabs;4     void Start () {5         GameStart.Instance.Show(prefabs);6     }7     8 }

基於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.