Unity 加载2D序列帧动画
程序员文章站
2022-03-25 21:32:44
...
利用Unity做2D游戏或者应用的时候,通常用到序列帧动画;
所需要播放的动画 通常有很多,所以构造一个动画类 来控制动画的播放会无比方便
以下是代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class AniSprite
{
private float speed;
private Sprite[] sprites;
private bool isPlay;
private int indexSprte;
private Image backImage;
private float timer;
//动画结束的事件
public UnityAction EndAniVoid;
/// <summary>
/// 构造方法
/// </summary>
/// <param name="动画播放速度"></param>
/// <param name="需要播放的序列帧"></param>
/// <param name="需要播放的容器(image)"></param>
public AniSprite(float _speed, Sprite[] _sprites, Image _backImage)
{
speed = _speed;
sprites = _sprites;
backImage = _backImage;
isPlay = false;
}
public void Pause()
{
isPlay = false;
}
public void Restore()
{
isPlay = true;
}
public void Play()
{
indexSprte = 0;
timer = 0;
isPlay = true;
//Debug.Log(isPlay);
//Debug.Log(isPlay);
}
public void Update()
{
if (isPlay.Equals(true))
{
timer += Time.deltaTime;
if (timer >= speed)
{
if (indexSprte >= sprites.Length)
{
//Debug.Log("序列动画结束");
if (EndAniVoid != null)
{
EndAniVoid();
}
isPlay = false;
return;
}
backImage.sprite = sprites[indexSprte];
indexSprte++;
timer = 0;
}
}
}
}
测试调用:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class testss : MonoBehaviour
{
public Sprite[] testSprites;
public Image testBackImage;
AniSprite ani;
// Start is called before the first frame update
void Start()
{
ani = new AniSprite(0.02f, testSprites, testBackImage);
ani.Play();
ani.EndAniVoid += delegate ()
{
Debug.Log("动画播放结束");
};
}
// Update is called once per frame
void Update()
{
if (ani!=null)
{
ani.Update();
}
}
}
**注意:实例化动画类是,需要将类的 update方法 一直执行,如上图所示
利用此类我做了一个 适应于夜场的小游戏 效果展示
如果有想要此项目或者源码 亦或者想要深入了解的朋友可以与我联系
QQ:237603564