Is there any easy way exists that animates frames without using Animator component?
1 Answer
\$\begingroup\$
\$\endgroup\$
Yes, here is the basic scrip I wrote with some help of anonymous somewhere on the internet. Script contains some of his code. Well, anyone can use it. I will improve it by time.
Here is the script:
using UnityEngine;
using System.Collections;
public class AnimationScript : MonoBehaviour
{
[Header("Animate Once?")]
[Tooltip("Either animation should run once or not.")]
// Either animation should run once or not
public bool
_animateOnce = false;
[Header("Time")]
[Tooltip("Time in seconds to change frames.")]
// Time in seconds to change frames
public float
_time = 1.0f;
[Header("Sprites")]
[Tooltip("Animation sprites.")]
// Animation sprites
public Sprite[]
_sprites;
int frameCount = 0;
SpriteRenderer spriteRenderer;
void OnEnable ()
{
frameCount = 0;
spriteRenderer = GetComponent<Renderer> () as SpriteRenderer;
StartCoroutine ("Animate");
}
void OnDisable ()
{
frameCount = 0;
StopCoroutine ("Animate");
}
// Use this for initialization
void Start ()
{
frameCount = 0;
spriteRenderer = GetComponent<Renderer> () as SpriteRenderer;
StartCoroutine ("Animate");
}
// Update is called once per frame
void Update ()
{
}
IEnumerator Animate ()
{
if (frameCount >= _sprites.Length) {
if (_animateOnce) {
yield break;
} else {
frameCount = 0;
}
}
if (_sprites [frameCount] == null)
yield break;
spriteRenderer.sprite = _sprites [frameCount];
frameCount++;
yield return new WaitForSeconds (Mathf.Abs (_time));
StartCoroutine ("Animate");
}
public void StopAnimation ()
{
StopCoroutine ("Animate");
}
}
Any suggestions are always welcome.