多个模块,单例模式的优化

在unity中,常常需要脚本间的相互调用

多个模块,单例模式的优化

等到脚本越来越多,可能会变成这样:

多个模块,单例模式的优化

这样非常不利于更新代码,如果继续添加,互相调用越来越复杂,就越来越难以维护,因此,我们可以这样

多个模块,单例模式的优化

各个代码都保存在guide中,其他脚本只要调用guide就能得到其他脚本,极大减少各个组件互相获取的时间,优化结构。

然后,我们可以把guide做成一个单例模式,这样任何脚本都能方便的获取组件,而不用一个一个调用效率极低的find方法。

当然你也可以把这些功能都做成单例,但那样会导致静态的变量过多,可能浪费内存。

下面放一个简单的示例:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Guide : MonoBehaviour {

    #region 单例模式
    private static Guide _root;
    public static Guide Root
    {
        get
        {
            if (_root == null)
                _root = new Guide();
            return _root;
        }
    }
    #endregion
    
    public GameManager gameManager;
    public MapManager mapManager;
    public Player player;
    public UIManager uiManager;

    private void Awake()
    {
        gameManager = GameObject.Find("....").GetComponent<GameManager>();
        mapManager = GameObject.Find("....").GetComponent<MapManager>();
        player = GameObject.Find("....").GetComponent<Player>();
        uiManager = GameObject.Find("....").GetComponent<UIManager>();
    }
}

这里单例写成root只是为了方便读写,提高可读性(懒)

按照标准写法应该是Instance