SequenceFrameHandler.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class SequenceFrameHandler : MonoBehaviour
  6. {
  7. [SerializeField] private List<Sprite> frames;
  8. private float fps = 15f;
  9. private Image image;
  10. private bool isAnimationPlaying = false;
  11. [SerializeField] private bool playOnStart = false;
  12. public bool reverse = false;
  13. private bool allowLoop = true;
  14. // ==================================================
  15. private void Start() => Init();
  16. // ==================================================
  17. private void Init()
  18. {
  19. image = GetComponent<Image>();
  20. if (playOnStart)
  21. {
  22. Play();
  23. }
  24. return;
  25. }
  26. // ==================================================
  27. public void Reset()
  28. {
  29. if (!reverse)
  30. {
  31. image.sprite = frames[0];
  32. }
  33. else
  34. {
  35. image.sprite = frames[frames.Count - 1];
  36. }
  37. return;
  38. }
  39. public void Play()
  40. {
  41. if (isAnimationPlaying)
  42. {
  43. return;
  44. }
  45. isAnimationPlaying = true;
  46. StartCoroutine(nameof(AnimationAction));
  47. return;
  48. }
  49. public void Stop()
  50. {
  51. if (!isAnimationPlaying)
  52. {
  53. return;
  54. }
  55. isAnimationPlaying = false;
  56. StopCoroutine(nameof(AnimationAction));
  57. return;
  58. }
  59. private IEnumerator AnimationAction()
  60. {
  61. // while (allowLoop) // 注释则不循环
  62. // {
  63. if (!reverse)
  64. {
  65. for (int i = 0; i < frames.Count; i++)
  66. {
  67. yield return new WaitForSeconds(1f / fps);
  68. image.sprite = frames[i];
  69. }
  70. }
  71. else
  72. {
  73. for (int i = frames.Count - 1; i > 0; i--)
  74. {
  75. yield return new WaitForSeconds(1f / fps);
  76. image.sprite = frames[i];
  77. }
  78. }
  79. // }
  80. }
  81. }