revival/game/Assets/Scripts/UI/SpriteAnimLoop.cs

69 lines
1.4 KiB
C#
Raw Permalink Normal View History

2021-03-11 12:48:17 +01:00
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SpriteAnimLoop : MonoBehaviour
{
[SerializeField]
private SpriteRenderer _renderer;
[SerializeField]
private Image _image;
[System.Serializable]
private struct SpriteFrame
{
public Sprite Sprite;
public float ShowTime;
}
[SerializeField]
private SpriteFrame[] _frames;
private float _time;
private int _spriteIndex;
public void ResetAnim()
{
_time = 0f;
_spriteIndex = 0;
}
private void OnEnable()
{
ResetAnim();
}
private void Update()
{
if ( _frames.Length == 0 )
return;
bool update = false;
_time += Time.unscaledDeltaTime;
while ( _time > _frames[ _spriteIndex ].ShowTime )
{
_time -= _frames[ _spriteIndex ].ShowTime;
_spriteIndex = (_spriteIndex + 1) % _frames.Length;
update = true;
}
if ( update )
{
var sprite = _frames[ _spriteIndex ].Sprite;
if (_renderer != null)
{
_renderer.sprite = sprite;
}
if ( _image != null )
{
_image.sprite = sprite;
}
}
}
}