首页 > 解决方案 > 如何在 C# 中只影响一个委托侦听器?

问题描述

所以我在每个播放器上都有一个 ManaScript 和一个 ManaBar。问题是,Manabar 监听每个 OnManaPercentChanged,因此即使每个游戏对象都有自己的 ManaScript 并且我在一个特定实例上调用 ModifyMana,ManaBar 也会为每个玩家更新。我应该如何着手只更换一个 ManaBar?

手稿:

[SerializeField] const int maxMana = 100;
int currentMana;  

public event Action<float> OnManaPercentChange = delegate { };

private void Awake()
{
    currentMana = maxMana;
}


public void ModifyMana(int amount)
{
    currentMana += amount;
    float currentManaPct = (float)currentMana / (float)maxMana;
    OnManaPercentChange(currentManaPct);
}

法力条:

[SerializeField] private Image foregroundImage;

private void Awake()
{
    GetComponentInParent<PlayerMana>().OnManaPercentChange += HandleManachanged;
}

private void HandleManachanged(float percent)
{
    foregroundImage.fillAmount = percent;
}

标签: c#unity3deventsdelegates

解决方案


推荐阅读