- Home /
[SOLVED] How I can detect deleted gameobject
How I can detect when particular gameobject with tag Player gets deleted so I can show an game over message? Please help in c# as I'm learning that.
Answer by clunk47 · Jul 20, 2013 at 02:42 AM
EDIT: Here is the working version of the script. Edited and tested, working fine for me.
using UnityEngine;
using System.Collections;
public class Valikko : MonoBehaviour
{
GameObject Pallo;
int bricksLeft;
bool destroyedAllBricks = false;
void Start ()
{
Pallo = GameObject.FindGameObjectWithTag("Player");
}
void Update ()
{
GameObject[] bricks = GameObject.FindGameObjectsWithTag("Brick");
bricksLeft = bricks.Length;
if(Input.GetKeyDown(KeyCode.A))
{
if(bricks.Length > 0)
Destroy (bricks[bricks.Length - 1]);
}
if(bricksLeft <= 0)
{
destroyedAllBricks = true;
}
}
void OnGUI ()
{
if(Pallo == null)
{
GUI.Box (new Rect (0,60,200,25),"Game Over!");
}
if(destroyedAllBricks)
{
GUI.Box (new Rect (0,30,200,25),"All bricks destroyed!");
}
else
{
GUI.Box (new Rect(0,30,200,25),"Bricks remaining :" + bricksLeft);
GUI.Box (new Rect (0,0,200,25), "CrazyBricks 3D v0.2");
GUI.Box (new Rect (Screen.width -300,0,300,25), "Broken Signal Entertainment (c) 2013");
}
}
}
Remove the semicolon after if(Pallo == null); You shouldn't have an if statement like if(this);{}, has to be if(this){}. I can tell it's a simple type-o because your other if statements are fine.
Ok I took the script and made some $$anonymous$$or adjustments. Working fine on my end. I used an object tagged "Player" and some cubes tagged "Brick" everything works fine. I edited my answer with the new version of the script. Hope it works on your end now.
The problem is, you actually need to delete the bricks to change the count since the count will always be the actual amount of bricks in the scene. Hitting a key and saying bricksLeft-- won't work. Don't maximize the scene on runtime, and delete each brick from the hierarchy, your count will subtract.
$$anonymous$$ake sure there is nothing else tagged as Player. Once player is destroyed, this should print ("player does not exist!". This tells us something is causing the player not to be null. I am getting game over message once player object is destroyed when I try this script on my machine. In what way are you destroying player? Are you doing with another script? When I test I delete player from hierarchy when game is running, and get game over message. Try this to see if player is simply being destroyed or not.
Ahh, it was because I was only setting that object inactive when it hit the ground. Now when I changed it to Destroy command it works just fine. Thank you for all the trouble you went through while trying to solve this problem which was so stupid and small that I should had known this..