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<Sprite>(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<Image>()
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
}
}