简体   繁体   English

是否有没有NetworkBehaviour的[SyncVar(hook =“ OnChangeHealth”))之类的功能?

[英]Is there a function like [SyncVar(hook = “OnChangeHealth”)] without NetworkBehaviour?

Is there a function in Unity, that you can use like this: Unity中是否有一个可以像这样使用的函数:

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

to run a method everytime a variable changes, just without the need of NetworkBehaviour? 在每次变量更改时都运行方法,而无需NetworkBehaviour?

I'm not aware of a simple attribute you can use, however - I generally go for something like this - 我不知道您可以使用一个简单的属性,但是-我通常会选择类似的东西-

    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();
            }
        }
    }

You'd need to subscribe to the event in another class for it to be notified, eg 您需要在另一个类中订阅该事件,以便将其通知,例如

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM