- Home /
How to loop an array of 2d sprites
I have been working on this code for school that handles animating 2D sprites on the 3D screen, just like a GUI. But I only have one sprite showing on the screen and I want to be able to animate it with the rest of the pictures I have (about 10). Here is the basic class I am working on:
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class AnimateSprites : MonoBehaviour {
public Texture2D mSprite;
public Rect r_Sprite;
void OnGUI()
{
GUI.DrawTexture(mSprite,r_Sprite);
}
}
How can I get this to loop the rest of my images? I know I have to go about making my sprite texture into arrays and also have a method which loops them. Can anyone help direct me on what my step(s) should be? Thank you in advance!
Answer by StormSabotage · Dec 10, 2013 at 03:19 PM
Try this:
public Texture2D[] mSprites;
private Texture2D currentSprite;
private int counter;
public float switchTime = 0.5f;
public Rect r_Sprite;
void Start(){
counter = 0;
StartCoroutine("SwitchSprite");
}
void OnGUI(){
GUI.DrawTexture(r_Sprite,currentSprite);
}
private IEnumerator SwitchSprite(){
currentSprite = mSprites[counter];
if(counter < mSprites.Length){
counter++;
}else{
counter = 0;
}
yield return new WaitForSeconds(switchTime);
StartCoroutine("SwitchSprite");
}
Just fill mSprites array with your sprites and set switchTime how you want ;)
You shouldn't use OnGUI for this look into Sprites.
Thanks, it worked for me too!
The only problem is that it changes sprites way too slow, and it doesn't matter the time I set it seems it always loops at the sime velocity.
I've used SpriteRenderer ins$$anonymous$$d of OnGUI, don't know if that is the problem.
Thanks again!