Unity C#单例模式的实现
生活随笔
收集整理的這篇文章主要介紹了
Unity C#单例模式的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、添加單例模板類
?
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;
?
原文地址:?http://blog.csdn.net/cocos2der/article/details/47335197
轉載于:https://www.cnblogs.com/UnrealEra/p/5896592.html
總結
以上是生活随笔為你收集整理的Unity C#单例模式的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: eclipse安装快速打开项目所在位置的
- 下一篇: Oracle将NetBeans交给了Ap