using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using System; [RequireComponent(typeof(Image))] public class UGUISpriteAnimation : MonoBehaviour { private Image ImageSource; private int mCurFrame = 0; private float mDelta = 0; public float FPS = 16; //public List SpriteFrames; public bool IsPlaying = false; public bool Foward = true; public bool AutoPlay = true; public bool Loop = false; public Action OnAnimationEndEvent; private string _containerName; public int FrameCount { get { return SpriteFrames.Count; } } /// /// 资源 /// private Dictionary SpriteFrames = new Dictionary(); /// /// /// /// /// public void Init(string frameContainer, Action onInitFinished) { _containerName = frameContainer; ImageSource = GetComponent(); ResourceHelper.Instance.LoadAssetBundle(frameContainer, (AssetBundle bundle) => { if (null != bundle) { GameObject go = (GameObject)bundle.LoadAsset(frameContainer); List tempList = go.GetComponent().mSpriteList; for (int i = 0; i < tempList.Count; i++) { if (null != tempList[i]) { SpriteFrames[tempList[i].name] = tempList[i]; } } //SpriteFrames = go.GetComponent().mSpriteList; } if (onInitFinished != null) { onInitFinished(); } }); } public void StartPlayAnimation() { if (AutoPlay) { Play(); } else { IsPlaying = false; } } private void SetSprite(int idx) { string resname = "frame (" + (idx + 1) + ")"; ImageSource.sprite = SpriteFrames[resname]; ImageSource.SetNativeSize(); //IconManager.Instance.GetSprite(_containerName, resname, texture => //{ // ImageSource.overrideSprite = texture; // ImageSource.SetNativeSize(); //}); } public void Play() { IsPlaying = true; Foward = true; } public void PlayReverse() { IsPlaying = true; Foward = false; } void Update() { if (!IsPlaying || 0 == FrameCount) { return; } mDelta += Time.deltaTime; if (mDelta > 1 / FPS) { mDelta = 0; if (Foward) { mCurFrame++; } else { mCurFrame--; } if (mCurFrame >= FrameCount) { InvokeEndEvent(); if (Loop) { mCurFrame = 0; } else { IsPlaying = false; return; } } else if (mCurFrame < 0) { InvokeEndEvent(); if (Loop) { mCurFrame = FrameCount - 1; } else { IsPlaying = false; return; } } SetSprite(mCurFrame); } } private void InvokeEndEvent() { if (OnAnimationEndEvent != null) { OnAnimationEndEvent(); } } public void Pause() { IsPlaying = false; } public void Resume() { if (!IsPlaying) { IsPlaying = true; } } public void Stop() { mCurFrame = 0; SetSprite(mCurFrame); IsPlaying = false; } public void Rewind() { mCurFrame = 0; SetSprite(mCurFrame); Play(); } }