# What is wrong with my Respawn coroutine?

I am creating a 2D Platformer game in which if the player falls off the base/ground then I want the player to respawn at the nearest checkpoint. However I want there to be a delay between the player falling off the ground and the respawn. This is the section of my code to achieve this goal:

private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log(collision.tag);
if (collision.tag.Equals("Kill"))
{
StartCoroutine("Respawn");
}
else if(collision.tag.Equals("Checkpoint"))
{

Animator flag = collision.GetComponent<Animator>();
if (!flag.GetBool("hasCrossed"))
{
flagCounter++;
flag.SetBool("hasCrossed", true);
checkpoint = collision.gameObject.transform.position;
}
}
}

IEnumerator Respawn()
{
yield return new WaitForSeconds(respawnDelay);
transform.position = checkpoint;

}


This works fine for small respawn delays like 1 or 2 seconds. But on increasing the delay to 5 seconds, the player after appearing at the nearest checkpoint vanishes off in an instant and then after quite a few repetitions the player reappears.

This is for the 2 second time delay

This is for the 5 second time delay

How can I fix this?

• Love the animated screenshots! – Konerak May 2 '18 at 12:24
• also known as gifs – user1306322 May 2 '18 at 16:10

This doesn't seem to have anything to do with how you set up the coroutine. What is probably happening is that the player gets a high enough acceleration while falling to glitch past the ground and the fallout collider. When you move the position during the respawn, it will still be falling at the same rate. In your Respawn method, sometime after your wait line, set the velocity back to zero: GetComponent<Rigidbody2D>().velocity = Vector2.zero.