• Unity3D 单例(singleton)管理类


    在Unity3D中,有什么好的方法去创建一个单例游戏管理类,可以像一个全局类的静态变量一样到处访问?

    在Unity中有什么接口吗?我是否要把这个脚本添加到一个物体上呢?这个类可以仅仅放在文件夹里不用添加到场景里吗?

    通常来说视情况而定,常用的两种单例类。

    (1)组件式的添加在物体上。

    (2)不从MonoBehaviour继承的独立类。

    public class MainComponentManger {
        private static MainComponentManger instance;
        public static void CreateInstance () {
            if (instance == null) {
                instance = new MainComponentManger ();
                GameObject go = GameObject.Find ("Main");
                if (go == null) {
                    go = new GameObject ("Main");
                    instance.main = go;
                    // important: make game object persistent:
                    Object.DontDestroyOnLoad (go);
                }
                // trigger instantiation of other singletons
                Component c = MenuManager.SharedInstance;
                // ...
            }
        }
    
        GameObject main;
    
        public static MainComponentManger SharedInstance {
            get {
                if (instance == null) {
                    CreateInstance ();
                }
                return instance;
            }
        }
    
        public static T AddMainComponent <T> () where T : UnityEngine.Component {
            T t = SharedInstance.main.GetComponent<T> ();
            if (t != null) {
                return t;
            }
            return SharedInstance.main.AddComponent <T> ();
        }

    当其它单例类想要注册Main 的组件时只要这样:

    public class AudioManager : MonoBehaviour {
        private static AudioManager instance = null;
        public static AudioManager SharedInstance {
            get {
                if (instance == null) {
                    instance = MainComponentManger.AddMainComponent<AudioManager> ();
                }
                return instance;
            }
        }

    原文链接:http://stackoverflow.com/questions/13730112/unity3d-singleton-manager-classes

  • 相关阅读:
    推荐20个开源项目托管网站
    python 网络编程(网络基础之网络协议篇)
    python 异常处理
    python 内置函数的补充 isinstance,issubclass, hasattr ,getattr, setattr, delattr,str,del 用法,以及元类
    python3 封装之property 多态 绑定方法classmethod 与 非绑定方法 staticmethod
    python3 类 组合
    PYTHON3中 类的继承
    面向对象 与类
    包 与常用模块
    json 与pickle模块(序列化与反序列化))
  • 原文地址:https://www.cnblogs.com/vital/p/3924679.html
Copyright © 2020-2023  润新知