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?