Unity Singleton class (20 of Unity3D development), singletonunity3d
Monkey original, reprinted. Reprinted Please note: Reprinted from the Cocos2Der-CSDN, thank you!
Address: http://blog.csdn.net/cocos2der/article/details/47335197
Today, I saw a friend in the Group asking about the best implementation method of the unity Singleton. I often use it below. Post it for your reference.
1. Add a singleton template class
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; }}
This is a singleton template class, which is easy to use.
2. define your own Singleton class
using UnityEngine;using System;public class GameManager : Singleton<GameManager> { public float score; void Awake () { this.Init(); } private void Init() { // Init code }}
Iii. Call and use
GameManager.Instance.score = 99;
If you have a better implementation method, we recommend that you.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.