Unity Singleton 單例類(Unity3D開發之二十),singletonunity3d

來源:互聯網
上載者:User

Unity Singleton 單例類(Unity3D開發之二十),singletonunity3d

猴子原創,歡迎轉載。轉載請註明: 轉載自Cocos2Der-CSDN,謝謝!
原文地址: http://blog.csdn.net/cocos2der/article/details/47335197

今天看到群裡有朋友問unity單例的最佳實現方式,下面我我經常用的。貼出來供大家參考。

一、添加單例模板類
using UnityEngine;public class Singleton<T> : MonoBehaviour where T : MonoBehaviour{    private static T _instance;    private static object _lock = new object ();    public static T Instance     {        get {            if (applicationIsQuitting) {                return null;            }            lock (_lock) {                if (_instance == null) {                    _instance = (T)FindObjectOfType (typeof(T));                    if (FindObjectsOfType (typeof(T)).Length > 1) {                        return _instance;                    }                    if (_instance == null) {                        GameObject singleton = new GameObject ();                        _instance = singleton.AddComponent<T> ();                        singleton.name = "(singleton) " + typeof(T).ToString ();                        DontDestroyOnLoad (singleton);                    }                }                return _instance;            }        }    }    private static bool applicationIsQuitting = false;    public void OnDestroy ()    {        applicationIsQuitting = true;    }}

這是一個單例模板類,使用就很簡單了。

二、定義自己的單例類
using UnityEngine;using System;public class GameManager : Singleton<GameManager> {    public float score;    void Awake () {        this.Init();    }    private void Init() {        // Init code    }}
三、調用使用
GameManager.Instance.score = 99;

如果有更好的實現方式,可以推薦下哦。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.