StarsIndicator.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. public class StarsIndicator : MonoBehaviour
  5. {
  6. public Slider slider;
  7. public StarTarget star1, star2, star3;
  8. int _maxScore;
  9. float _maxWidth;
  10. void Awake()
  11. {
  12. //Get the width from the slider's sprites
  13. _maxWidth = slider.GetComponent<RectTransform>().sizeDelta.x;
  14. slider.value = 0;
  15. }
  16. void OnEnable()
  17. {
  18. NotificationCenter.AddListener(OnScoreChanged, NotificationType.UpdateScoreLabel);
  19. var level = LevelsManager.Instance.CurrentLevel;
  20. SetStarPositions(level.star1Threshold, level.star2Threshold, level.star3Threshold);
  21. }
  22. void OnDisable()
  23. {
  24. NotificationCenter.RemoveListener(OnScoreChanged, NotificationType.UpdateScoreLabel);
  25. }
  26. void SetStarPositions(int star1Threshold, int star2Threshold, int star3Threshold)
  27. {
  28. _maxScore = star3Threshold;
  29. star1.SetPosition(star1Threshold, _maxScore, _maxWidth);
  30. star2.SetPosition(star2Threshold, _maxScore, _maxWidth);
  31. star3.SetPosition(star3Threshold, _maxScore, _maxWidth);
  32. }
  33. void OnScoreChanged(Notification note)
  34. {
  35. int score = GameDataManager.Instance.Score;
  36. float newSliderValue = score / (float)_maxScore;
  37. iTween.Stop(gameObject);
  38. iTween.ValueTo(gameObject, iTween.Hash(
  39. "from", slider.value,
  40. "to", newSliderValue,
  41. "time", 0.3f,
  42. "onupdate", "OniTweenUpdateSlider",
  43. "onupdatetarget", gameObject));
  44. }
  45. void OniTweenUpdateSlider(float newValue)
  46. {
  47. slider.value = newValue;
  48. }
  49. }