//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
///
/// Small script that makes it easy to create looping 2D sprite animations.
///
public class UI2DSpriteAnimation : MonoBehaviour
{
///
/// How many frames there are in the animation per second.
///
[SerializeField] protected int framerate = 20;
///
/// Should this animation be affected by time scale?
///
public bool ignoreTimeScale = true;
///
/// Should this animation be looped?
///
public bool loop = true;
///
/// Actual sprites used for the animation.
///
public UnityEngine.Sprite[] frames;
UnityEngine.SpriteRenderer mUnitySprite;
UI2DSprite mNguiSprite;
int mIndex = 0;
float mUpdate = 0f;
///
/// Returns is the animation is still playing or not
///
public bool isPlaying { get { return enabled; } }
///
/// Animation framerate.
///
public int framesPerSecond { get { return framerate; } set { framerate = value; } }
///
/// Continue playing the animation. If the animation has reached the end, it will restart from beginning
///
public void Play ()
{
if (frames != null && frames.Length > 0)
{
if (!enabled && !loop)
{
int newIndex = framerate > 0 ? mIndex + 1 : mIndex - 1;
if (newIndex < 0 || newIndex >= frames.Length)
mIndex = framerate < 0 ? frames.Length - 1 : 0;
}
enabled = true;
UpdateSprite();
}
}
///
/// Pause the animation.
///
public void Pause () { enabled = false; }
///
/// Reset the animation to the beginning.
///
public void ResetToBeginning ()
{
mIndex = framerate < 0 ? frames.Length - 1 : 0;
UpdateSprite();
}
///
/// Start playing the animation right away.
///
void Start () { Play(); }
///
/// Advance the animation as necessary.
///
void Update ()
{
if (frames == null || frames.Length == 0)
{
enabled = false;
}
else if (framerate != 0)
{
float time = ignoreTimeScale ? RealTime.time : Time.time;
if (mUpdate < time)
{
mUpdate = time;
int newIndex = framerate > 0 ? mIndex + 1 : mIndex - 1;
if (!loop && (newIndex < 0 || newIndex >= frames.Length))
{
enabled = false;
return;
}
mIndex = NGUIMath.RepeatIndex(newIndex, frames.Length);
UpdateSprite();
}
}
}
///
/// Immediately update the visible sprite.
///
void UpdateSprite ()
{
if (mUnitySprite == null && mNguiSprite == null)
{
mUnitySprite = GetComponent();
mNguiSprite = GetComponent();
if (mUnitySprite == null && mNguiSprite == null)
{
enabled = false;
return;
}
}
float time = ignoreTimeScale ? RealTime.time : Time.time;
if (framerate != 0) mUpdate = time + Mathf.Abs(1f / framerate);
if (mUnitySprite != null)
{
mUnitySprite.sprite = frames[mIndex];
}
else if (mNguiSprite != null)
{
mNguiSprite.nextSprite = frames[mIndex];
}
}
}