Advertisement
infinite_ammo

SpriteAnimation.cs

Jan 26th, 2013
531
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [System.Serializable]
  5. public class Animation
  6. {
  7.     public string name;
  8.     public float delay;
  9.     public Texture2D[] textures;
  10.     public bool loop;
  11.    
  12.     [HideInInspector]
  13.     public int frame;
  14.    
  15.     public void NextFrame()
  16.     {
  17.         frame++;
  18.        
  19.         if (frame >= textures.Length)
  20.         {
  21.             if (loop)
  22.             {
  23.                 frame = 0;
  24.             }
  25.             else
  26.             {
  27.                 frame = textures.Length - 1;
  28.             }
  29.         }
  30.     }
  31. }
  32.  
  33. public class SpriteAnimation : MonoBehaviour
  34. {
  35.     public Animation[] animations;
  36.    
  37.     public float speed = 1f;
  38.    
  39.     public bool isPlaying { get; private set; }
  40.     public float timer { get; private set; }
  41.    
  42.     private Animation currentAnimation;
  43.    
  44.     public void Play(string name)
  45.     {
  46.         Animation animation = GetAnimation(name);
  47.         if (animation != null)
  48.         {
  49.             currentAnimation = animation;
  50.             currentAnimation.frame = 0;
  51.             isPlaying = true;
  52.             timer = 0f;
  53.             SetCurrentFrame();
  54.         }
  55.     }
  56.    
  57.     public Animation GetAnimation(string name)
  58.     {
  59.         foreach (Animation animation in animations)
  60.         {
  61.             if (animation.name == name)
  62.                 return animation;
  63.         }
  64.         return null;
  65.     }
  66.    
  67.     void SetCurrentFrame()
  68.     {
  69.         if (currentAnimation != null)
  70.         {
  71.             renderer.material.mainTexture = currentAnimation.textures[currentAnimation.frame];
  72.         }
  73.     }
  74.    
  75.     void Update()
  76.     {
  77.         if (isPlaying)
  78.         {
  79.             if (currentAnimation != null)
  80.             {
  81.                 timer += Time.deltaTime * speed;
  82.                
  83.                 while (timer > currentAnimation.delay)
  84.                 {
  85.                     currentAnimation.NextFrame();
  86.                     timer -= currentAnimation.delay;
  87.                 }
  88.                
  89.                 SetCurrentFrame();
  90.             }
  91.         }
  92.     }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement