using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Image))] public class UIFrame : MonoBehaviour { [SerializeField] private string frameKey = string.Empty; private List sprites = null; private int index = 0; private bool run = false; private Image m_Image; private float m_Interval = 0.1f; private int loopCount = 0; //0表示无限循环 private void Awake() { m_Image = GetComponent(); } private void OnEnable() { Run(); } public void ResetFrame(string key) { TimeMgr.Instance.UnRegister(m_Image); frameKey = key; Run(); } void Run() { if (m_Image==null||frameKey.Equals(string.Empty)) return; if (!gameObject.activeInHierarchy) { return; } sprites = UIFrameMgr.Inst.GetDynamicImage(frameKey); if (sprites == null||sprites.Count<1) { Debug.LogError(string.Format("没有{0}对应的帧动画", frameKey)); enabled = false; return; } run = true; int timeLoopCount = loopCount * sprites.Count; //计算总循环次数 动画的一个循环是所有图片播放一遍 m_Image.overrideSprite = sprites[0]; if (sprites.Count == 1) return; index = 1; FrameAnimationConfig cfg = FrameAnimationConfig.Get(frameKey); if (cfg != null&& cfg.speed > 0) { m_Interval = 1.0f / cfg.speed; } TimeMgr.Instance.Register(m_Image, OnSpriteAnim, m_Interval, timeLoopCount); } void OnSpriteAnim(Component comp) { if (!run) return; if (!TimeMgr.Instance.IsRegister(comp)) { this.SetActive(false); return; } if (sprites==null) { TimeMgr.Instance.UnRegister(m_Image); return; } if (index < 0 || index >= sprites.Count) { index = 0;return; } m_Image.overrideSprite = sprites[index]; index++; if (index >= sprites.Count) index = 0; } public void SetLoopCount(int count) { loopCount = count; } private void OnDisable() { run = false; TimeMgr.Instance.UnRegister(m_Image); } }