using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
namespace MYTOOL.UI
{
[RequireComponent(typeof(Image))]
public class UISpriteAnimation : MonoBehaviour
{
[SerializeField]
private byte FPS = 10;
[SerializeField]
private bool AutoPlay = true;
public bool Foward = true;
public bool Loop = true;
[Space]
public List<Sprite> SpriteFrames;
public Action<int> OnFrameCallback;
public Action OnComplete;
private Image ImageSource;
private int mCurFrame;
private float mDelta;
public bool IsPlaying { get; private set; }
public int FrameCount
{
get
{
return SpriteFrames.Count;
}
}
void Awake()
{
ImageSource = GetComponent<Image>();
IsPlaying = AutoPlay;
}
void Start()
{
mCurFrame = Foward ? 0 : FrameCount - 1;
SetSprite(mCurFrame);
}
void Update()
{
if (!IsPlaying || 0 == FrameCount) return;
mDelta += Time.deltaTime;
if (mDelta > 1f / FPS)
{
mDelta = 0;
mCurFrame += Foward ? 1 : -1;
if (mCurFrame >= FrameCount || mCurFrame < 0)
{
if (Loop)
{
mCurFrame = mCurFrame >= FrameCount ? 0 : FrameCount - 1;
}
else
{
IsPlaying = false;
OnComplete?.Invoke();
return;
}
}
SetSprite(mCurFrame);
}
}
public void Play()
{
IsPlaying = true;
}
public void Stop()
{
mCurFrame = Foward ? 0 : FrameCount - 1;
SetSprite(mCurFrame);
IsPlaying = false;
}
private void SetSprite(int idx)
{
ImageSource.sprite = SpriteFrames[idx];
ImageSource.SetNativeSize();
OnFrameCallback?.Invoke(idx);
}
}
}
unity 播放图片序列帧
于 2024-12-07 21:20:19 首次发布