Files
3d-bianpo/Assets/Scripts/Anim/SpriteAnim.cs
2026-03-03 11:30:53 +08:00

89 lines
1.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SpriteAnim : MonoBehaviour
{
public bool isLoop = true;
public float timer = 0.1f;
public Sprite[] frames;
private int index = 0;
private SpriteRenderer spriteRender;
private Image image;
void Awake()
{
spriteRender = GetComponent<SpriteRenderer>();
image = GetComponent<Image>();
}
void Start()
{
index = 0;
Play();
}
public void Play()
{
CancelInvoke("PlayAnim");
InvokeRepeating("PlayAnim", 0f, timer);
}
public void Stop()
{
CancelInvoke("PlayAnim");
}
public void Reset()
{
if (index >= frames.Length)
{
CancelInvoke("PlayAnim");
return;
}
index = 0;
if (spriteRender != null)
{
spriteRender.sprite = frames[index];
}
if (image != null)
{
image.sprite = frames[index];
}
}
void PlayAnim()
{
if (index >= frames.Length)
{
CancelInvoke("PlayAnim");
return;
}
if (spriteRender != null)
{
spriteRender.sprite = frames[index];
}
if (image != null)
{
image.sprite = frames[index];
}
index++;
if (index >= frames.Length)
{
if (isLoop)
{
index = 0;
}
else
{
CancelInvoke("PlayAnim");
}
}
}
}