当前位置:   UNITY > 正文

[Unity] 单例设计模式, 可供继承的单例组件模板类

[Unity] 单例设计模式, 可供继承的单例组件模板类

一个可供继承的单例组件模板类:

public class SingletonComponent<TComponent> : MonoBehavior
    where TComponent : SingletonComponent<TComponent>
{
    static TComponent _instance;

    private static TComponent GetOrFindOrCreateComponent()
    {
       // 双检索
        if (_instance == null)
        {
            // 尝试在场景中查找已存在的组件
            _instance = FindObjectOfType<TComponent>();
            
            // 如果找不到, 则创建一个空对象, 并且挂载上组件
            if (_instance == null)
            {
                GameObject gameObject = new GameObject();
                _instance = gameObject.AddComponent<TComponent>();
            }
        }

        return _instance;
    }

    public static TComponent Instance => GetOrFindOrCreateComponent();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

因为 Unity 是单线程的, 所以在这里没有必要使用双检索


使用方式

例如你要创建一个全局的单例管理类, 可以这样使用:

public class GameManager : SingletonComponent<GameManager>
{
    // your code here
}
  • 1
  • 2
  • 3
  • 4

注意事项

尽量避免让 SingletonComponent 帮你创建组件, 因为它只是单纯的将组件创建, 并挂载到空对象上, 而不会进行任何其他行为. 如果你的组件需要进行某些初始化, 那么它可能不会正常.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/UNITY/detail/35220
推荐阅读
相关标签
  

闽ICP备14008679号