【Unity】游戏中的单例

游戏中需要一些 GameObject(例如网络管理器) 在游戏的整个生命周期都存在,而且是以单例的形式存在。

 XGame 中实现这种单例的方式是,单例脚本都从 MonoSingle 类继承,MonoSingleton 的实现方法是在 Awake() 中调用DontDestroyOnLoad(gameObject);来保证单例。
MonoSingleton类的实现代码:
 1 /// <summary>
 2 /// Generic Mono singleton.
 3 /// </summary>
 4 using UnityEngine;
 5 
 6 public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>{
 7     
 8     private static T mInstance = null;
 9     
10     public static T Instance{
11         get{
12             return mInstance;
13         }
14     }
15 
16     private void Awake(){
17    
18         if (mInstance == null)
19         {
20             DontDestroyOnLoad(gameObject);
21             mInstance = this as T;
22             mInstance.Init();
23         }
24         else
25         {
26             Destroy(gameObject);
27         }
28     }
29  
30     public virtual void Init(){}
31 
32     public virtual void Fini(){}
33  
34 
35     private void OnApplicationQuit(){
36         mInstance.Fini();
37         mInstance = null;
38     }
39 }

需要单例控制的脚本,只要从 MonoSigleton 类继承就可以了,重写 Init 方法来实现单例自己的初始化,重写 Fini 实现自己的清理工作。例如:

posted @ 2014-09-26 17:30  没有113  阅读(1503)  评论(1编辑  收藏  举报