102 lines
2.4 KiB
C#
102 lines
2.4 KiB
C#
using UnityEngine;
|
||
using System.Collections;
|
||
using UnityEngine.UI;
|
||
|
||
public class FrameAnimation : MonoBehaviour
|
||
{
|
||
[Header("动画设置")]
|
||
[SerializeField] private Sprite[] frameSprites; // 序列帧数组(拖入125张图片)
|
||
[SerializeField] private float totalTime = 5f; // 总时长
|
||
[SerializeField] private bool loop = true; // 是否循环播放
|
||
|
||
private Image img;
|
||
private int totalFrames;
|
||
private float frameInterval;
|
||
private Coroutine animationCoroutine;
|
||
|
||
void Start()
|
||
{
|
||
InitializeComponents();
|
||
ValidateFrameData();
|
||
CalculateFrameInterval();
|
||
StartAnimation();
|
||
}
|
||
|
||
void InitializeComponents()
|
||
{
|
||
img = GetComponent<Image>();
|
||
if (img == null)
|
||
{
|
||
img = gameObject.AddComponent<Image>();
|
||
}
|
||
}
|
||
|
||
void ValidateFrameData()
|
||
{
|
||
if (frameSprites == null || frameSprites.Length == 0)
|
||
{
|
||
Debug.LogError("请分配序列帧图片!");
|
||
enabled = false;
|
||
return;
|
||
}
|
||
|
||
totalFrames = frameSprites.Length;
|
||
if (totalFrames != 125)
|
||
{
|
||
Debug.LogWarning("建议使用125帧获得精确时长,当前帧数:" + totalFrames);
|
||
}
|
||
}
|
||
|
||
void CalculateFrameInterval()
|
||
{
|
||
// 计算每帧持续时间(总时长 / 总帧数)
|
||
frameInterval = totalTime / totalFrames;
|
||
}
|
||
|
||
public void StartAnimation()
|
||
{
|
||
if (animationCoroutine != null)
|
||
{
|
||
StopCoroutine(animationCoroutine);
|
||
}
|
||
animationCoroutine = StartCoroutine(PlayAnimation());
|
||
}
|
||
|
||
IEnumerator PlayAnimation()
|
||
{
|
||
int currentFrame = 0;
|
||
|
||
do
|
||
{
|
||
// 更新当前帧
|
||
img.sprite = frameSprites[currentFrame];
|
||
// 等待帧间隔时间
|
||
yield return new WaitForSeconds(frameInterval);
|
||
|
||
// 递增帧索引
|
||
currentFrame = (currentFrame + 1) % totalFrames;
|
||
|
||
} while (loop || currentFrame != 0); // 循环控制
|
||
|
||
animationCoroutine = null;
|
||
}
|
||
|
||
void OnDisable()
|
||
{
|
||
if (animationCoroutine != null)
|
||
{
|
||
StopCoroutine(animationCoroutine);
|
||
animationCoroutine = null;
|
||
}
|
||
}
|
||
|
||
// 在Inspector修改参数时实时更新
|
||
void OnValidate()
|
||
{
|
||
if (Application.isPlaying && animationCoroutine != null)
|
||
{
|
||
CalculateFrameInterval();
|
||
StartAnimation();
|
||
}
|
||
}
|
||
} |