在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、添加单例模板类
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 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论