- Home /
Clear reference when destroying gameobject
Hi!
var coolObject : GameObject;
function DestroyObject(){
Destroy(coolObject);
}
function TestForObject(){
if(coolObject == null){
Debug.Log("It's gone");
}
}
After coolObject got destroyed, how do i check if it is still there or not? Check == null gives me false.
Answer by szimmermann · Sep 25, 2016 at 07:28 PM
Destroy() will not change the value of the instance variable you pass to null. This has to be done by yourself.
If you write
function DestroyObject()
{
if( coolObject != null )
{
Destroy(coolObject);
coolObject=null;
Debug.Log("destroying cool object");
}
else
{
Debug.Log("It's gone");
}
}
you are always on the safe side, even if you are calling DestroyObject() multiple times from different code locations.
But i am not destroying the object from the same script. I really need a way to check if the object exists or not.
Answer by AurimasBlazulionis · Sep 25, 2016 at 07:29 PM
This should be null. There are few things to keep in mind. First if you call destroy and then check, it will not work because unity destroys things after the frame, not in between.
Second, the destroyed game object reference works weird, you should try checking if (shootTarget == null || shootTarget.Equals(null))
. This seems to solve issues for many.
Answer by meat5000 · Mar 28, 2017 at 05:15 PM
This is how to test for the existence of an object :
var coolObject : GameObject;
function DestroyObject()
{
Destroy(coolObject);
}
function TestForObject()
{
if(coolObject) // <-- Test occurs here
{
Debug.Log("Not gone");
}
else Debug.Log("Destroyed");
}
Answer by shadowpuppet · Mar 28, 2017 at 07:29 PM
I run into this often. I like to destroy things I don't need any more but often have that object referenced in some other script and I hate those red warnings saying I am trying to access something I destroyed more than having unneeded objects in the scene. So I just SetActive (false) or SpriteRenderer.enabled false or some other component of the object disabled once it has served it's purpose. Or if I destroy the object because no longer needed I also destroy the script that references it ( if it too is no longer of use) and if the reference to the destroyed object sits in a larger script and I really want to destroy the object I will put that reference in a different script
Your answer
![](https://koobas.hobune.stream/wayback/20220612093458im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Prevent destruction of an object's child 1 Answer
Collision Detection not working? 1 Answer
Spawned objects randomly not destroyed 1 Answer
Deleting objects from list sequence 1 Answer