ImageFillInterpolator.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. namespace Devdog.SciFiDesign.UI
  5. {
  6. public class ImageFillInterpolator : MonoBehaviour
  7. {
  8. [Range(0f, 1f)]
  9. [SerializeField]
  10. private float _from = 0f;
  11. public float from
  12. {
  13. get { return Mathf.Max(_from, minFrom); }
  14. }
  15. [Range(0f, 1f)]
  16. public float minFrom = 0f;
  17. [Range(0f, 1f)]
  18. [SerializeField]
  19. private float _to = 1f;
  20. public float to
  21. {
  22. get { return Mathf.Min(_to, maxTo); }
  23. }
  24. [Range(0f, 1f)]
  25. public float maxTo = 1f;
  26. public float startDelay = 0f;
  27. public AnimationCurve animationCurve = AnimationCurve.EaseInOut(0f, 0f, 1f, 1f);
  28. public float speed = 1f;
  29. private Image _image;
  30. public Image image
  31. {
  32. get { return _image; }
  33. }
  34. private float _timer = 0f;
  35. protected void Awake()
  36. {
  37. _image = GetComponent<Image>();
  38. InterpolateValue();
  39. }
  40. public void InterpolateValue(float to)
  41. {
  42. _to = to;
  43. InterpolateValue();
  44. }
  45. public void InterpolateValue(float from, float to)
  46. {
  47. _from = from;
  48. _to = to;
  49. InterpolateValue();
  50. }
  51. public void InterpolateValue()
  52. {
  53. StartCoroutine(_InterpolateValue());
  54. }
  55. protected IEnumerator _InterpolateValue()
  56. {
  57. _timer = 0f;
  58. _image.fillAmount = _from;
  59. yield return new WaitForSeconds(startDelay);
  60. while (_timer < 1f)
  61. {
  62. _timer += Time.deltaTime * speed;
  63. var val = Mathf.Lerp(_from, _to, _timer);
  64. _image.fillAmount = animationCurve.Evaluate(_timer) * val;
  65. yield return null;
  66. }
  67. }
  68. }
  69. }