gpt4 book ai didi

c# - 当另一个类变量发生变化时使用事件是否比直接访问该变量更有效?安全呢?属性呢?

转载 作者:行者123 更新时间:2023-11-30 12:22:05 24 4
gpt4 key购买 nike

我正在尽可能地简化情况:

第 1 类:

public class GameFlowManager { 
public float worldSpeed;
}

第 2 类:

public class Clouds {
void MoveClouds(float worldSpeed){...}

我需要访问 worldSpeed来自 Clouds .
哪种方式效率更高?

  • 使用 GameFlowManager gfm = FindObjectOfType<GameFlowManager>()然后通过指针 访问变量(我知道这不是真正的指针,但目的是一样的)
    像这样:gfm.worldSpeed
  • 或者我应该使用一个事件,它在需要 worldSpeed 的类(class)?这样我就不必做变量 public。

现在这只是为了统一,当我不能使用属性时。在简单的 C# 代码中,我可以使用 getter 而不会产生任何后果,对吗?

最佳答案

对于以“Manager”结尾的所有内容(意味着可能只有一个),您应该使用单例模式,如下所示:

class GameFlowManager
{
public static GameFlowManager Instance {get; private set;}

public float worldSpeed{get; set;} // You could make the setter private to prevent other classes from modifying it if necessary

void Awake()
{
Instance = this; // Note that this requires an object of type GameFlowManager to already exist in your scene. You could also handle the spawning of this object automatically to remove this requirement.
}

...
}

然后,当您需要此类的值时,您可以:

GameFlowManager.Instance.worldSpeed

这个解决方案是完美的。


编辑:谁说不能在 unity 中使用属性?

关于c# - 当另一个类变量发生变化时使用事件是否比直接访问该变量更有效?安全呢?属性呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42607665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com