Skip to content

Instantly share code, notes, and snippets.

@shukerullah
Last active October 20, 2020 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shukerullah/70e7536774cf91fafb44e2a104480672 to your computer and use it in GitHub Desktop.
Save shukerullah/70e7536774cf91fafb44e2a104480672 to your computer and use it in GitHub Desktop.
Unity (Canvas) UI.Image Sprite Animation
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
[RequireComponent(typeof(Image))]
public class UISpriteAnimation : MonoBehaviour {
public Sprite[] sprites;
public int fps = 6;
public bool playOnAwake = true;
public bool loop = true;
public bool destroyOnEnd = false;
public UnityEvent onAnimationComplete;
private bool m_Play = false;
private int m_Index = 0;
private Image m_Image;
private int m_Frame = 0;
void Awake() {
m_Image = GetComponent<Image> ();
PlayOnAwake();
}
public void Play() {
EnableImage();
m_Index = 1;
m_Play = true;
}
public void Stop() {
DisableImage();
m_Index = 0;
m_Play = false;
}
void Update () {
if (!m_Play) {
return;
}
m_Frame ++;
if (m_Frame < fps) {
return;
}
m_Frame = 0;
if (m_Index >= sprites.Length) {
OnAnimationComplete();
}
m_Image.sprite = sprites [m_Index];
m_Index ++;
}
void OnAnimationComplete() {
m_Index = 0;
onAnimationComplete.Invoke();
if(destroyOnEnd) {
Destroy(gameObject);
} else if(!loop) {
Stop();
}
}
void PlayOnAwake() {
if(!playOnAwake) {
DisableImage();
} else {
Play();
}
}
void EnableImage() {
if(!m_Image.enabled) {
m_Image.enabled = true;
}
}
void DisableImage() {
if(m_Image.enabled) {
m_Image.enabled = false;
}
}
}
@shukerullah
Copy link
Author

Screen Shot 2020-10-20 at 6 14 59 PM

Public Methods

  • Play()
  • Stop()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment