zoukankan      html  css  js  c++  java
  • 【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 实现自己的清理工作。例如:

  • 相关阅读:
    JQuery中的回调对象
    CSS中的视觉格式化模型
    css中的选择器
    浅谈css中的position
    python-24: re 模块 之二 re方法及反斜杠
    python-23 xml.etree.ElementTree模块
    python-22 eval json pickle shelve 之间差别
    python-21 os 模块
    python-18: datetime 模块
    python-16: time 模块 之二
  • 原文地址:https://www.cnblogs.com/litterrondo/p/3995328.html
Copyright © 2011-2022 走看看