Unity中单例模式的应用___MonoSingleton

如果项目中有很多个单例,那么我们就必须每次都写这些代码,有什么办法可以省去这些不必要的代码呢?

 

using UnityEngine;

/// <summary>
/// Be aware this will not prevent a non singleton constructor
///   such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class.
/// 
/// As a note, this is made as MonoBehaviour because we need Coroutines.
/// </summary>
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;

    private static object _lock = new object();

    public static T Instance
    {
        get
        {
            if (applicationIsQuitting)
            {
                Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
                                 "' already destroyed on application quit." +
                                 " Won't create again - returning null.");
                return null;
            }

            lock (_lock)
            {
                if (_instance == null)
                {
                    _instance = FindObjectOfType<T>();

                    if (FindObjectsOfType<T>().Length > 1)
                    {
                        Debug.LogError("[Singleton] Something went really wrong " +
                                       " - there should never be more than 1 singleton!" +
                                       " Reopenning the scene might fix it.");
                        return _instance;
                    }

                    if (_instance == null)
                    {
                        GameObject singleton = new GameObject();


                        _instance = singleton.AddComponent<T>();
                        singleton.name = "(singleton) " + typeof(T).ToString();

                        DontDestroyOnLoad(singleton);

                        Debug.Log("[Singleton] An instance of " + typeof(T) +
                                  " is needed in the scene, so '" + singleton +
                                  "' was created with DontDestroyOnLoad.");
                    }
                    else
                    {
                        //Debug.Log("[Singleton] Using instance already created: " + _instance.gameObject.name);
                    }
                }

                return _instance;
            }
        }
    }

    private static bool applicationIsQuitting = false;
    /// <summary>
    /// When Unity quits, it destroys objects in a random order.
    /// In principle, a Singleton is only destroyed when application quits.
    /// If any script calls Instance after it have been destroyed, 
    ///   it will create a buggy ghost object that will stay on the Editor scene
    ///   even after stopping playing the Application. Really bad!
    /// So, this was made to be sure we're not creating that buggy ghost object.
    /// </summary>
    protected virtual void OnDestroy()
    {
        applicationIsQuitting = true;
    }
    public virtual void Awake()
    {
        if (gameObject.transform.parent == null)
            DontDestroyOnLoad(gameObject);
    }

}

应用:

public class AppMain : MonoSingleton<AppMain> { }

 

MonoBehavior单例

今天我们就来看看在unity中如何使用单例模式,在unity中,我们分两种单例,一种是继承monobehavior的单例,一种是普通单例。

其实在unity中,如果脚本是继承monobehavior,那么使用起单例来更加简单。

只需要在Awake()里面,添加一句instance = this;

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

using UnityEngine;

using System.Collections;

public class test2 : MonoBehaviour {

    public static test2 instance;

    // Use this for initialization

    void Awake () {

        instance = this;

    }

     

    // Update is called once per frame

    void Update () {

    }

}

  

2.普通类的单例

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

using UnityEngine;

using System.Collections;

public class test2 {

    private static test2 instance;

    public static test2 Instance

    {

        get

        {

            if (null == instance)

                instance = new test2();

            return instance;

        }

        set { }

    }

}

猜你喜欢

转载自blog.csdn.net/Le_Sam/article/details/79815619
今日推荐