当另一个 class 变量发生变化时使用事件是否比直接访问该变量更有效?安全呢?属性呢?
Is it more efficient to use events when another class variable changes than accessing the variable directly? What about safety? What about properties?
我正在尽可能地简化情况:
class 1:
public class GameFlowManager {
public float worldSpeed;
}
class 2:
public class Clouds {
void MoveClouds(float worldSpeed){...}
我需要从 Clouds
访问 worldSpeed
。
哪种方式效率更高?
- 使用
GameFlowManager gfm = FindObjectOfType<GameFlowManager>()
然后通过指针 访问变量(我知道这不是真正的
指针,但目的是一样的)
像这样:gfm.worldSpeed
- 或者我应该使用一个事件,在
class需要
worldSpeed
?这样我就不必做
变量 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.
}
...
}
然后,每当您需要此 class 中的值时,您可以:
GameFlowManager.Instance.worldSpeed
这个解决方案是完美的。
编辑:谁说不能在 unity 中使用属性?
我正在尽可能地简化情况:
class 1:
public class GameFlowManager {
public float worldSpeed;
}
class 2:
public class Clouds {
void MoveClouds(float worldSpeed){...}
我需要从 Clouds
访问 worldSpeed
。
哪种方式效率更高?
- 使用
GameFlowManager gfm = FindObjectOfType<GameFlowManager>()
然后通过指针 访问变量(我知道这不是真正的 指针,但目的是一样的)
像这样:gfm.worldSpeed
- 或者我应该使用一个事件,在
class需要
worldSpeed
?这样我就不必做 变量 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.
}
...
}
然后,每当您需要此 class 中的值时,您可以:
GameFlowManager.Instance.worldSpeed
这个解决方案是完美的。
编辑:谁说不能在 unity 中使用属性?