SequenceFrameHandler.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 = 12f;
  9. private Image image;
  10. private bool isAnimationPlaying = false;
  11. [SerializeField] private bool allowPlayOnStart = false;
  12. private bool allowLoop = true;
  13. // ==================================================
  14. private void Start() => Init();
  15. // ==================================================
  16. private void Init()
  17. {
  18. image = GetComponent<Image>();
  19. if (allowPlayOnStart)
  20. {
  21. SwitchAnimation(true);
  22. }
  23. return;
  24. }
  25. // ==================================================
  26. public void SwitchAnimation(bool value)
  27. {
  28. if (value)
  29. {
  30. if (isAnimationPlaying)
  31. {
  32. return;
  33. }
  34. isAnimationPlaying = true;
  35. StartCoroutine(nameof(AnimationAction));
  36. }
  37. else
  38. {
  39. if (!isAnimationPlaying)
  40. {
  41. return;
  42. }
  43. isAnimationPlaying = false;
  44. image.sprite = frames[0];
  45. StopCoroutine(nameof(AnimationAction));
  46. }
  47. return;
  48. }
  49. private IEnumerator AnimationAction()
  50. {
  51. while (allowLoop) // 注释则不循环
  52. {
  53. for (int i = 0; i < frames.Count; i++)
  54. {
  55. image.sprite = frames[i];
  56. yield return new WaitForSeconds(1f / fps);
  57. }
  58. }
  59. }
  60. }