Respawn Delay Not Working [Closed]

Hi,

I’m playing around with the “Space Shooter” project and am having trouble with Player respawns. Basically, what I want to do is respawn the player after a small delay using the WaitForSeconds function. Everything’s working fine except the delay and I have no idea why.

Here’s the code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class DestroyByContact : MonoBehaviour
{
	public GameObject explosion;
	public GameObject playerExplosion;
	public int scoreValue;
	private GameController gameController;
	
	void Start ()
	{
		GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
		if (gameControllerObject != null)
		{
			gameController = gameControllerObject.GetComponent <GameController>();
		}
		if (gameController == null)
		{
			Debug.Log ("Cannot find 'GameController' script");
		}
	}
	
	void OnTriggerEnter(Collider other) 
	{
		if (other.tag == "Boundary")
		{
			return;
		}

		Instantiate(explosion, transform.position, transform.rotation);

		if (other.tag == "Player")
		{
			Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
			gameController.lives -= 1;
			if (gameController.lives == 0)
			{
				gameController.GameOver ();
			}
			else
			{
				StartCoroutine (PlayerSpawnWait ());
				gameController.PlayerSpawn();
			}
		}
	
		gameController.AddScore (scoreValue);
		Destroy(other.gameObject);
		Destroy(gameObject);
	}
	public IEnumerator PlayerSpawnWait()
	
	{
		yield return new WaitForSeconds(2);
		Debug.Log ("Waiting...");
	}
}

All this gets me is an instant respawn. I’ve tried putting the PlayerSpawn function in the Coroutine and still no dice. Interestingly, if I put the Debug message in the PlayerSpawnWait coroutine above the WaitForSeconds function it shows up in the console, so clearly the coroutine is being called… it’s just the delay isn’t working.

Any ideas? Help much appreciated. :slight_smile:

Try putting line 45 just after your yield statement in PlayerSpawnWait() instead of just after the call to StartCoroutine().

EDIT: disregard the rest of this, it’s just me being dumb. Read the other answer about how to “lock a thread” :stuck_out_tongue:

Coroutines are kind of like threads. And the only thing you are doing in yours currently is waiting. While the “main thread” continues on like nothing happened. Which is why you get an instant spawn. Moving your spawn line into the coroutine “thread” should sort it out.

(I don’t think it’s really a thread. C# uses Tasks anyway, but I’m not really solid on it so I don’t want to mislead you at all. But “works” like a thread, and that’s good enough I think.)

A running coroutine will halt a main thread. The main code will not carry on regardless. You can test this by putting a infinite loop in your coroutine and watching your program grind to a halt.