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

原文地址:https://www.cnblogs.com/vital/p/3924679.html