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.