Anonim_999

HealthBar

Feb 3rd, 2022 (edited)
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.92 KB | None | 0 0
  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4.  
  5. [RequireComponent(typeof(Slider))]
  6. public class HealthBar : MonoBehaviour
  7. {
  8.     [SerializeField] private Hero _player;
  9.     [SerializeField] private float _maxDelta;
  10.  
  11.     private Slider _slider;
  12.    
  13.     private void OnEnable()
  14.     {
  15.         _player.HealthChanged += StartChangeValue;
  16.         _slider = GetComponent<Slider>();
  17.         _slider.maxValue = _player.MaxHealth;
  18.         _slider.value = _player.Health;
  19.     }
  20.  
  21.     private void OnDisable()
  22.     {
  23.         _player.HealthChanged -= StartChangeValue;
  24.     }
  25.  
  26.     public void StartChangeValue()
  27.     {
  28.         StartCoroutine(ChangeValue());
  29.     }
  30.  
  31.     private IEnumerator ChangeValue()
  32.     {
  33.         while (_slider.value != _player.Health)
  34.         {
  35.             _slider.value = Mathf.MoveTowards(_slider.value, _player.Health,_maxDelta);
  36.             yield return null;
  37.         }
  38.     }
  39. }
Add Comment
Please, Sign In to add comment