C# Unity : What's the difference between calling another class's function directly vs. 通过订阅事件调用函数?

标签 c# unity3d game-development

在游戏开发 (Unity C#) 中,我的脑海中总是有一个关于从另一个类调用函数的最佳方法或最佳方法的问题,我在这里使用了两种方法:

方法一

Making the function DoSomething public in class 1 and call it from class 2

第 1 类:

public class Class1 : MonoBehaviour{

    public static Class1 instance;

    private void Awake()
    {
        instance = this;
    }

    //The function we want to call
    public function DoSomething(){

        Debug.Log("Done something!");

    }

}

第 2 类:

public class Class2 : MonoBehaviour{

    private Class1 _class1;

    private void start(){
        _class1 = Class1.instance;
    }

    public function SomeFunction(){

        //Calling the function
        _class1.DoSomething();

    }

}

方法二

Creating an event in class 2 and subscribing to this event in class 1, this way the function will get called when we trigger the event in class 2

第 1 类:

public class Class1 : MonoBehaviour{


    private void OnEnable()
    {
        Class2.OnSomeEvent += DoSomething;
    }


    private void OnDisable()
    {
        Class2.OnSomeEvent -= DoSomething;
    }

    //The function we want to call
    private function DoSomething(){

        Debug.Log("Done something!");

    }

}

第 2 类:

public class Class2 : MonoBehaviour{

    public static event Action OnSomeEvent = delegate {};

    public function SomeFunction(){

        OnSomeEvent();

    }

}

这两种方法有什么区别,哪种方法的功能和性能最好?

最佳答案

性能取决于用例。假设您希望在玩家生命值低于特定值时对某个类运行某种方法。一种选择是在每次更新 时检查是否到了执行该操作的时间。然而,那将是低效的。更好的选择是订阅一个仅在健康状况发生变化时触发的事件,然后在那里进行健康检查。

除此之外,它还是开发项目架构的额外工具。无需将代码混合在一起,您可以使用一个类来处理在某些 X 事情发生时通知其他人,而其他人可以收听该事件。

关于C# Unity : What's the difference between calling another class's function directly vs. 通过订阅事件调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61576019/

相关文章:

ios - 收集硬币并添加到 Sprite Kit 中的分数标签

OpenGL 纹理数组将纹理完全渲染为黑色

c# - 在代码隐藏中使用 XDocument 时出错

unity3d - unity AudioSource.Play 有噪音

java - 将 Unity3D 项目导出并运行到 Android Studio

C# : How couroutine stop the loop

java - 游戏中撤消/重做功能的堆栈实现

c# - FirstOrDefault() 无法与 ??运算符(operator)

c# - TPL 和内存管理

c# - 如果列表字符串元素包含来自另一个列表的字符串元素,如何删除它?