80 lines
1.8 KiB
C#
80 lines
1.8 KiB
C#
|
using UnityEngine;
|
|||
|
using UnityEngine.UI;
|
|||
|
|
|||
|
[RequireComponent(typeof(Image))]
|
|||
|
public class UIAnimationFree : MonoBehaviour
|
|||
|
{
|
|||
|
private Image _image;
|
|||
|
private int _index;
|
|||
|
private float _nextTime;
|
|||
|
public int frameRate = 20;
|
|||
|
public bool loop = false;
|
|||
|
public Sprite[] sprites;
|
|||
|
|
|||
|
private void Awake()
|
|||
|
{
|
|||
|
_image = GetComponent<Image>();
|
|||
|
}
|
|||
|
|
|||
|
private void Update()
|
|||
|
{
|
|||
|
if (Time.time > _nextTime)
|
|||
|
{
|
|||
|
_index++;
|
|||
|
if (_index >= sprites.Length)
|
|||
|
{
|
|||
|
if (loop)
|
|||
|
{
|
|||
|
_index = 0;
|
|||
|
SetImage();
|
|||
|
_nextTime += GetFrameTime();
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
if (_waitTime == -1)
|
|||
|
{
|
|||
|
_nextTime = float.PositiveInfinity;
|
|||
|
StopAnimation();
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
_index = 0;
|
|||
|
SetImage();
|
|||
|
_nextTime = Time.time + _waitTime;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
SetImage();
|
|||
|
_nextTime += GetFrameTime();
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
private float GetFrameTime()
|
|||
|
{
|
|||
|
return 1f / Mathf.Max(1, frameRate);
|
|||
|
}
|
|||
|
|
|||
|
private void SetImage()
|
|||
|
{
|
|||
|
if (_index < sprites.Length)
|
|||
|
_image.sprite = sprites[_index];
|
|||
|
}
|
|||
|
|
|||
|
private float _waitTime = -1;
|
|||
|
public void ShowAnimationAfterTime(float time)
|
|||
|
{
|
|||
|
gameObject.SetActive(true);
|
|||
|
_waitTime = time;
|
|||
|
}
|
|||
|
|
|||
|
public void StopAnimation()
|
|||
|
{
|
|||
|
_index = 0;
|
|||
|
_waitTime = -1;
|
|||
|
if (gameObject.activeInHierarchy)
|
|||
|
gameObject.SetActive(false);
|
|||
|
}
|
|||
|
}
|