- Home /
The question is answered, right answer was accepted
Probem when trying to create a coroutine
I am trying to create a coroutine, but for some reason visual studio doesn't like it, can somebody help me:
public IEnumerator RespawnPlayerCo() {
Instantiate(deathParticle, player.transform.position, player.transform.rotation);
player.transform.position = currentCheckPoint.transform.position;
player.GetComponent<Rigidbody2D>().velocity = Vector3.zero;
Instantiate(respawnParticle, player.transform.position, player.transform.rotation);
}
It doesn't like the part where it says "RespawnPlayerCo" it says that not all code paths return a value.
Answer by UnityCoach · Aug 15, 2017 at 06:43 PM
A CoRoutine must implement at least one yield statement.
You can do the following :
public IEnumerator RespawnPlayerCo()
{
Instantiate(deathParticle, player.transform.position, player.transform.rotation);
player.transform.position = currentCheckPoint.transform.position;
player.GetComponent<Rigidbody2D>().velocity = Vector3.zero;
Instantiate(respawnParticle, player.transform.position, player.transform.rotation);
yield return true; // or
yield return new WaitForSeconds (1f);
}
Never suggest to use
yield return true;
or
yield return 0f;
This is pointless and just generate garbage. A boolean value, a float value or int value are all value types. They need to be boxed when passed around as object. Boxing requires the temporary creation of a box object on the heap.
If you want to wait for the next frame, always use
yield return null;
Thanks @Bunny83, I'll keep that in $$anonymous$$d ;)