AlpakaJoe
AlpakaJoe

Reputation: 593

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

Is there a function in Unity, that you can use like this:

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

to run a method everytime a variable changes, just without the need of NetworkBehaviour?

Upvotes: 0

Views: 223

Answers (1)

Daniel Matthews
Daniel Matthews

Reputation: 171

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, e.g.

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

Upvotes: 3

Related Questions