Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- [System.Serializable]
- public class Animation
- {
- public string name;
- public float delay;
- public Texture2D[] textures;
- public bool loop;
- [HideInInspector]
- public int frame;
- public void NextFrame()
- {
- frame++;
- if (frame >= textures.Length)
- {
- if (loop)
- {
- frame = 0;
- }
- else
- {
- frame = textures.Length - 1;
- }
- }
- }
- }
- public class SpriteAnimation : MonoBehaviour
- {
- public Animation[] animations;
- public float speed = 1f;
- public bool isPlaying { get; private set; }
- public float timer { get; private set; }
- public Animation currentAnimation { get; private set; }
- public void Play(string name)
- {
- PlayFromFrame(name, 0);
- }
- public void PlayFromFrame(string name, int frame)
- {
- Animation animation = GetAnimation(name);
- if (animation != null)
- {
- currentAnimation = animation;
- currentAnimation.frame = frame;
- isPlaying = true;
- timer = 0f;
- SetCurrentFrame();
- }
- }
- public Animation GetAnimation(string name)
- {
- foreach (Animation animation in animations)
- {
- if (animation.name == name)
- return animation;
- }
- return null;
- }
- void SetCurrentFrame()
- {
- if (currentAnimation != null)
- {
- renderer.material.mainTexture = currentAnimation.textures[currentAnimation.frame];
- }
- }
- void Update()
- {
- if (isPlaying)
- {
- if (currentAnimation != null)
- {
- if (currentAnimation.delay > 0f)
- {
- timer += Time.deltaTime * speed;
- while (timer > currentAnimation.delay)
- {
- currentAnimation.NextFrame();
- timer -= currentAnimation.delay;
- }
- }
- SetCurrentFrame();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement