As per the title, I’m trying to code an animation from scratch. So I created an object (“GeoObject”) that contains an array of sprites, and has a SpriteRenderer component. Using the WaitForSecondsRealTime() function, I am trying to have GeoObject loop through its sprites at a given rate. But the problem is that, when it comes time to switch, instead of going to the next sprite in the array, the object just starts very rapidly switching between all the sprites. It ends up looking like the object is spazzing out. My code is below and I would really appreciate any help with this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
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(0, shapes.Length - 1);
renderer.sprite = shapes[spriteIndex];
}
// Update is called once per frame
void Update () {
// Falling speed
float yspeed = -20f;
transform.Translate(0, yspeed * Time.deltaTime, 0);
// Loops through shapes
StartCoroutine(ChangeShape());
}
IEnumerator ChangeShape()
{
// Pauses execution for however many seconds
yield return new WaitForSecondsRealtime(delay);
var renderer = GetComponent<SpriteRenderer>();
if ( spriteIndex < shapes.Length - 1 ) { spriteIndex++; }
else { spriteIndex = 0; }
renderer.sprite = shapes[spriteIndex];
StartCoroutine(ChangeShape());
}
}