Hey wonderful Unity friends! I’m new to coroutines but I think they will work well for my use case here. I’m just struggling to stop my first coroutine after the condition is met.
Here’s the goal:
- Grow the object until y = 15
- Once y = 15, halt the object growth and wait for 2 seconds
- After 2 seconds, shrink object
But here’s what’s happening instead:
- Object is growing smoothly until y = 15
- Once y = 15, the object sporadically shrinks and grows
- Both “grow” and “shrink” coroutines keep getting called together
Here’s the code I’ve written so far. It’s invoked after an object is instantiated with a click, which is why I’m not using the Start function. I’m thinking that Update might be part of the issue?
public class ExplosionScript : MonoBehaviour
{
Vector3 scaleChange = new Vector3(.03f, .03f);
public GameObject selectedObject;
void Update()
{
if (selectedObject.transform.localScale.y < 15f)
{
StartCoroutine("Grow");
}
//Problem: debug.log tells me both "Grow" and "Shrink" are getting called even after condition is met:
else if (selectedObject.transform.localScale.y > 15f)
{
StopCoroutine("Grow");
StartCoroutine("Shrink");
}
}
IEnumerator Grow()
{
selectedObject.transform.localScale += scaleChange;
Debug.Log("growing");
yield return null;
}
IEnumerator Shrink()
{
yield return new WaitForSeconds(2f);
selectedObject.transform.localScale += -scaleChange;
Debug.Log("shrinking");
yield return null;
}