Difference Between Destroying instance.gameObject and instance?

Hello,

I noticed when Gary destroys the ParticleSystem in the method PlayHitEffect(), he writes Destroy(instance.gameObject) whereas in other cases he would simply write Destroy(instance). I’ve tried out both ways of destroying the ParticleSystem but haven’t noticed a difference during gameplay, so I’d like to ask what the difference is? Thank you (:

Hi ttgm,

If you have a game object with only one component attached (apart from Transform), and you destroy the component, you won’t notice any difference in your game. The ‘empty’ game object will continue to live in the Hierarchy, though, which is a potential waste of resources in larger games. If we spawn multiple instances of this specific prefab, we could end up with hundreds if not thousands of empty game objects which might even negatively affect a small game like a mobile game on a mobile device.

In many cases, we don’t have just one component on a game object.

If you understood the difference, the questions for your game are: What exactly do you want to destroy, and why do you want to destroy it? Then apply your knowledge to find the ‘best’ solution for your specific problem. Gary and Rick did the same, which is why you see different ‘versions’ in the videos.

Is this what you wanted to know? :slight_smile:


See also:

You (almost) always want to destroy the gameObject. As @Nina mentioned, you’d end up with a bunch of unnecessary game objects in the scene otherwise.

In the course, Gary uses Destroy(instance.gameObject) in PlayHitEffect() because instance is a reference to ParticleSystem and he wants to destroy the gameObject that this ParticleSystem belongs to instead of just the ParticleSystem. He gets the gameObject it belongs to by means of the gameObject field. In the Shooter script he uses Destroy(instance, projectileLifetime). instance is already a reference to a gameObject so there’s no need to get the instance.gameObject because instance is the gameObject. In all other cases in the course, Gary uses Destroy(gameObject) which destroys the gameObject the current script belongs to. Again, he’s using the gameObject field, but this time it belongs to the current script.

So in this course, Gary is always destroying the gameObject, whether it’s the gameObject the ParticleSystem belongs to, the projectile gameObject or any other gameObject that needs destroying.

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

Privacy & Terms