首页 > 代码库 > 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
Unity C#单例模式的实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。