Destroy(gameObject) is triggering error

At the end of lecture 99 at the 2d unity course we add the function
void OnCollisionEnter2D(Collision2D other)
{
Destroy(gameObject);
}

this triggers “MissingRefrenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.”

Happens on the first shot and from what I see it completely destroys the prefab.
I am not sure how to solve it as it doesn’t happen in the lecture and I even downloaded the scripts from the lecture to make sure it is not something I have done.

Hi,

Welcome to our community! :slight_smile:

Prefabs must not and cannot be destroyed during runtime. Are you referring to a game object in your Hierarchy? If so, which game object might get destroyed? Is it the one you pass on to the Destroy method? If so, try to figure out what might be trying to access it.

thank you, happy to be here !

yes, it is the gameObject we use as “Bullet” sorry for not being clear.
it should only destroy the instantiate() clones.
I am using the exact same code and exact values to minimize my chance of error but it still occurs.

without the last function that we added(on collision enter 2d) this does not happen.
since I am using the code from the project changes it leads me to believe it might be an error that derives from unity changes, but I am not sure.

You might be right. Objects get destroyed at the end of the frame. If the Bullet object “destroys” a game object and that game object still accesses things until the end of the frame, one might get this error message.

Unfortunately, there is no flag in the Unity code we could check whether a game object was flagged as “destroyed”. At least, I was not able to find it.

You could try to disable the “other” game object where you call Destroy: other.gameObject.SetActive(false);. Then the Update methods of its components won’t get executed anymore.

When I see this, it’s usually when I’ve referencing a gameObject from the scene instead of a prefab. If the referenced gameObject is destroyed and you try to Instantiate from it again, it hits this error.

Try checking if your bullet is a gameObject within the scene. If it is, link the prefab instead.

1 Like

Thank you both @MichaelP @Nina for you help

It was indeed as you said, the bullet was within the scene, or close enough to reach it which destroyed it.
:slight_smile:
I moved it down and it worked! thank you!
furthermore I referenced it from the prefab as you suggested and it works better :slight_smile:

I’m glad Michael knew the problem and the solution. Debugging this could have been a bit challenging. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms