Unity3D脚本逐帧播放指定文件夹下的图片

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class GifPlayTest : MonoBehaviour
{
    [SerializeField] private Image image;
    [Header("sprite渲染组件")] public Sprite[] sprites;
    [Header("Resources下的路径")] public string resPath;
    [Header("是否赋值了")] public bool isGenerate = false;

    public bool needRevert = false;
    private bool isDestroy = false;
    private bool isFromToEnd = true;

    private void Start()
    {
        PlayAnimation();
    }

    private void Update()
    {
        FindSprites();
    }

    private void FindSprites()
    {
        if (isGenerate)
        {
            // 重新设置sprites数组的长度,
            // 不然当资源的数量少于上次的资源的时候sprites
            // 超出的数组长度会变成空值
            sprites = new Sprite[0];
            // 赋值给sprites
            sprites = Resources.LoadAll(resPath);
            // 当点击isGenerate时,立即设为false,以保证每次点击只执行一次
            isGenerate = false;
        }
    }

    private int AnimationAmount
    {
        get
        {
            if (sprites == null)
            {
                return 0;
            }

            return sprites.Length;
        }
    }

    public void PlayAnimation()
    {
        if (image == null) image = GetComponent();
        if (AnimationAmount == 0)
        {
            FindSprites();
        }

        StartCoroutine(PlayAnimationForwardIEnum());
    }

    private IEnumerator PlayAnimationForwardIEnum()
    {
        int index = 0; //可以用来控制起始播放的动画帧索引
        gameObject.SetActive(true);
        while (true)
        {
            if (isDestroy)
            {
                break;
            }

            //当我们需要在整个动画播放完之后 重复播放后面的部分 就可以展现我们纯代码播放的自由性
            if (index > AnimationAmount - 1)
            {
                if (needRevert)
                {
                    isFromToEnd = false;
                    index = AnimationAmount - 1;
                }
                else
                {
                    index = 0;
                }
            }else if (index < 0)
            {
                index = 0;
                isFromToEnd = true;
            }

            image.sprite = sprites[index];
            if (isFromToEnd)
            {
                index++;
            }
            else
            {
                index--;
            }
            yield return new WaitForSeconds(0.03f); //等待间隔 控制动画播放速度
        }
    }

    private void OnDestroy()
    {
        isDestroy = true;
    }
}

你可能感兴趣的:(Unity3D脚本逐帧播放指定文件夹下的图片)