在游戏开发 (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/