有没有NetworkBehaviour的[SyncVar(hook =“OnChangeHealth”)]这样的函数?

时间:2018-06-13 11:31:24

标签: c# unity3d

Unity中是否有一个功能,您可以这样使用:

[SyncVar(hook = "OnChangeHealth")]
int health;

每次变量运行一个方法,只需要不需要NetworkBehaviour?

1 个答案:

答案 0 :(得分:3)

我不知道你可以使用的简单属性,但是 - 我通常会选择这样的东西 -

    public class HealthComponent : MonoBehaviour
    {
        [SerializeField]
        private int _maxHealth;

        [SerializeField]
        private int _currentHealth;

        public delegate void HealthChanged();
        public event HealthChanged HealthChangedEvent;

        public void ChangeHealth(int amountToChangeBy)
        {            
            _currentHealth += amountToChangeBy;
            if (_currentHealth > _maxHealth)
            {
                _currentHealth = _maxHealth;
            }
            if (_currentHealth < 0)
            {
                _currentHealth = 0;
            }
            if (HealthChangedEvent != null)
            {
                HealthChangedEvent();
            }
        }
    }

您需要在另一个类中订阅该事件,以便通知它,例如

public class HealthSliderComponent : MonoBehaviour
{
    [SerializeField]
    private Slider _healthSlider;

    private HealthComponent _healthComponent;

    private void Awake()
    {
        _healthComponent = GetComponent<HealthComponent>();
        _healthComponent.HealthChangedEvent += HandleHealthChanged;
    }

    private void HandleHealthChanged()
    {
        _healthSlider.value = _healthComponent.CurrentHealth;
    }
}