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.

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.

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.

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");
 }

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