例如,假设我们在一个脚本中有一个health变量,并希望在UI脚本中访问该变量以显示health,另一方面,根据health的数量改变声音的音调。
我知道一些访问这个变量的方法,但是它们之间高度依赖脚本。比如GetComponent、Singelton甚至C#event。
编辑:
这个事件系统是在我的脑海中,但我认为它有一些依赖性,他们可以删除,但我不知道如何,我也不确定它和它的性能。
public class Player {
public class HealthEventArgs : EventArgs {
public int currentHealth;
public HealthChangedEventArgs(int currentHealth) {
this.currentHealth = currentHealth;
}
}
public static event EventHandler<HealthEventArgs> HealthEvent;
public void NotifyHealthChanged(int health) {
if(HealthEvent != null) {
HealthEvent.Invoke(this, new HealthEventArgs(health));
}
}
}
public class OtherClass {
public void SubscribeToPlayerHealthEvent() {
Player.HealthEvent += Foo;
}
public void UnsubscribeFromPlayerHealthEvent() {
Player.HealthEvent -= Foo;
}
public void Foo(object o, HealthEventArgs e) {
//Do something with e.currentHealth
}
}