I want to show a game over GUI without getting rid of anything else going on in the scene upon player death. But the player is destroyed upon their death, so when I add the GameOver component, it just gets destroyed right away (and gives me some errors). How can I get around this?
Here is what I have, although it does not work:
//Death is a component of the player.
//I have other stuff going on in death too,
//so getting rid of it is something I want to avoid
using UnityEngine;
using System.Collections;
public class Death : MonoBehaviour
{
private bool applicationClosing;
void OnApplicationQuit()
{
applicationClosing = true;
}
void OnDestroy()
{
if (applicationClosing)
{
return;
}
//GameOver is my Game Over GUI Script
gameObject.AddComponent<GameOver>();
}
}
The simplest method, it to add new object on a scene. I hope that you destroy only one GameObject, instead of all scene:
void OnDestroy() {
if (applicationClosing) {
return;
}
//GameOver is my Game Over GUI Script
GameObject gmo = new GameObject(); //create new object
gmo.name = "myGUIscript"; //change name
gmo.AddComponent<GameOver>(); //add your component at object
}
You are adding your GameOver component to your player object which is getting destroyed so once your player object is destroyed that component will not be available since it is destroyed with your player object. And you might be trying to access the GameOver component on your player object from other scripts.
So what you can do is create an empty game object and add your GameOver component to that object and then enable that game object from your Death script. So even if your player is destroyed your GameOver component is available to access for other scripts from the empty game object to which it is assigned to.
This can be done something like this:
public GameObject gameOverGameObject;
void OnDestroy()
{
if (applicationClosing)
{
return;
}
//GameOver is my Game Over GUI Script
gameOverGameObject.SetActive(true);
}
Here GameOverGameObject is the name of your empty game object which has the GameOver component attached to it already. Assing that Game Object to the gameOverGameObject variable from the script and also at the start set this game object to be disabled.