I’m basically coding an animation from scratch. The GameObject in question (“GeoObject”) transitions between four different shapes. These shapes are contained as sprites in an Array (called “shapes”) within the GeoObject. There is code set up so that the array index loops according to the length of the array. Then, the Sprite Renderer changes the sprite of GeoObject accordingly. However, for some reason, the array index keeps going out of bounds, which shouldn’t happen in my code, as far as I can tell. Could someone take a look at the code below and help me figure out what I’m doing wrong? I would really appreciate it.
public class GeoObject : MonoBehaviour {
public Sprite[] shapes;
public float delay = 2.0f;
public int spriteIndex = 0;
// Use this for initialization
void Start () {
var renderer = GetComponent<SpriteRenderer>();
// Randomizes the starting shape
System.Random rand = new System.Random();
spriteIndex = rand.Next(1, shapes.Length);
renderer.sprite = shapes[spriteIndex];
}
// Update is called once per frame
void Update () {
// Loops through shapes
StartCoroutine(ChangeShape());
}
IEnumerator ChangeShape()
{
yield return new WaitForSeconds(delay); // Pauses execution for however many seconds
var renderer = GetComponent<SpriteRenderer>();
// This should loop through the array of sprites
if ( spriteIndex < shapes.Length ) { spriteIndex++; }
else { spriteIndex = 1; }
renderer.sprite = shapes[spriteIndex]; // Index keeps going out of bounds
StartCoroutine(ChangeShape());
}
}