[Unity技巧]单例基类

参考链接:http://www.redblack.cn/?p=100


在unity中有两种单例类型,一种是普通单例,即普通c#类,另一种是继承了MonoBehaviour的单例。

普通单例:

public abstract class CSharpSingletion<T> where T : new() {

    private static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new T();
            }
            return instance;
        }
    }

}

using UnityEngine;
using System.Collections;

public class AudioSingletion : CSharpSingletion<AudioSingletion> {

    public int i = 1;
}


继承了MonoBehaviour的单例:

using UnityEngine;
using System.Collections;

public abstract class MonoSingletion<T> : MonoBehaviour where T : MonoBehaviour {

    private static string rootName = "MonoSingletionRoot";
    private static GameObject monoSingletionRoot;

    private static T instance;
    public static T Instance
    {
        get
        {
            if (monoSingletionRoot == null)
            {
                monoSingletionRoot = GameObject.Find(rootName);
                if (monoSingletionRoot == null) Debug.Log("please create a gameobject named " + rootName);
            }
            if (instance == null)
            {
                instance = monoSingletionRoot.GetComponent<T>();
                if (instance == null) instance = monoSingletionRoot.AddComponent<T>();
            }
            return instance;
        }
    }

}

using UnityEngine;
using System.Collections;

public class MusicSingletion : MonoSingletion<MusicSingletion> {

    public void PrintInfo()
    {
        print("Music!!!!!!!!!!");
    }
}

你可能感兴趣的:(单例基类)