using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Image))] public class UiAnimation : MonoBehaviour { private Image _image; private int _index; private float _nextTime; public float frameRate = 20f; public float delayBetweenCycle; public bool loop = true; public Sprite[] sprites; private void Awake() { _image = GetComponent(); } private void OnEnable() { SetIndex(0); } private void Update() { if (Time.time > _nextTime) { _index++; if (_index >= sprites.Length) { if (loop) { _index = 0; SetImage(); _nextTime += GetFrameTime(); } else { _nextTime = float.PositiveInfinity; } } else { SetImage(); if (_index < sprites.Length - 1) _nextTime += GetFrameTime(); else _nextTime += Mathf.Max(GetFrameTime(), delayBetweenCycle); } // 防止一次渲染帧越过太多动画帧,然后导致动画快速播放 _nextTime = Mathf.Max(_nextTime, Time.time); } } private float GetFrameTime() { return 1f / Mathf.Max(1, frameRate); } private void SetImage() { if (_index < sprites.Length) _image.sprite = sprites[_index]; } public void SetIndex(int index) { _index = Mathf.Min(index, sprites.Length - 1); SetImage(); _nextTime = Time.time + GetFrameTime(); } }