I am trying to call a coroutine once, whenever the user scores a point, I should be hitting the UpdateSpeed function. It doesn’t seem to be working if I call it like I do in the “test” function below. Is this possible with Unity’s implementation of coroutines?
public void test()
{
UpdateSpeed();
}
public IEnumerator UpdateSpeed()
{
Debug.Log("Update Speed");
...
}
I am doing it this way because I don’t want the UpdateSpeed function to check the points every frame, only when a point is added.
The Update Speed debug message is not showing up at all, why doesn’t this work?
Coroutines are not called like regular functions; The syntax is different. They are “started” with StartCoroutine():
StartCoroutine(UpdateSpeed());
If you want to be able to stop them while they are running, you have to start them by passing their name as a string. In this case, you can only pass one parameter, but you can work around this limitation by passing it a custom class which in turn holds all necessary values.
Actually, what you are doing is not calling a Coroutine. To call a Coroutine you need to do
StartCoroutine(UpdateSpeed());
Then, to prevent your code to call it multiple times, just add a boolean check.
If what you want to achieve is to destroy a previously called coroutine before calling it again, you just need to stop the coroutine.
IEnumerator myRoutine;
public void callTheRoutine()
{
if (myRoutine == null)
myRoutine = StartCoroutine (UpdateSpeed());
else
StopCoroutine (myRoutine);
}
public IEnumerator UpdateSpeed ()
{
Debug.Log ("Hello");
yield return new WaitForSeconds (1.0f);
Debug.Log ("world !");
}
You still need to start it normally using StartCoroutine. As long as you don’t have any looping in your Coroutine it will just run through everything, doing any yields or whatever, then exit out as soon as you don’t return anything.