Hi all,
I have a GUI script that calls upon the Player object in order to populate the Health and ammo counters. When my player dies, there is a two-to-three second delay before they are respawned. However, this means that (since I am still using onGUI() for my simple GUI boxes), I get an error, since the Player no longer exists, has not yet been instantiated, and thus cannot have its Scripts or attributes (including Health, ammo, etc) read off from it. The relevant code is here:
void OnGUI(){
//making sure game doesn't crash if if there's nulls
if (Theplayer == null) {
Theplayer = GameObject.FindGameObjectWithTag("Player");
}
if (playersArm == null) {
playersArm = Theplayer.transform.FindChild("Arm");
}
if (musket == null) {
musket = playersArm.FindChild ("Musket").GetComponent<Musket> ();
}
if (crossbow == null) {
crossbow = playersArm.FindChild("Crossbow").GetComponent<Crossbow> ();
}
musketBallStock = musket.ammo.ToString();
crossbowBoltStock = crossbow.ammo.ToString();
//Drawing the ammo boxes
if (crossbow.active && crossbow.enabled && crossbow!= null) {
GUI.Box (new Rect (0, Screen.height - 50, 100, 50), crossbowBoltStock);
} else if (musket.active && musket.enabled && musket != null) {
GUI.Box (new Rect (0, Screen.height - 50, 100, 50), musketBallStock);
} else {
GUI.Box (new Rect (0, Screen.height - 50, 100, 50), "");
}
//Drawing Health Box
GUI.Box (new Rect (0, Screen.height - 100, 100, 50), Theplayer.GetComponent<Player>().playerStats.Health.ToString());
}
and, in case it’s relevant, here’s the respawn code (in a totally different script, but it might still be of use):
public IEnumerator respawnPlayer(){//Notice that the return type is no longer void, but IEnumerator, since we YIELD a new WaitForSeconds object
audio.Play ();
yield return new WaitForSeconds (spawnDelay);
Instantiate (playerPrefab, spawnPoint.position, spawnPoint.rotation);
GameObject clone = Instantiate (spawnPrefab, spawnPoint.position, spawnPoint.rotation) as GameObject;
Destroy (clone, 3f); //This line destroys the particles after 3 seconds. They fade out anyway, but they're still technically there and could cause problems if the project gets complex.
//need to re-set the "target" attribute in EnemyAI.cs at this point, or it will crash because the Player it was assigned to chase will have been deleted
}
Does anyone have any ideas as to how I might prevent this conflict from occurring?
Thanks