- Home /
Remove "this" Component
If I add a Component to a GameObject using gameObject.addComponent();, and I want to remove that component from the MyComponent C# file, is there anyway I can do something like:
Destroy(this);
instead of:
Destroy(gameObject.GetComponent<MyComponent>();
I know the latter works, but it just bugs me that I have to specify the name of the component that I am in.
Answer by Bunny83 · Sep 17, 2014 at 02:45 AM
Of course you can use
Destroy(this);
Keep in mind that this will only destroy the component but keep the GameObject and all other components. The Destroy method works with all instance-references that are derived from UnityEngine.Object. This includes GameObjects, Components, Meshes, Materials, ...
Unfortunately they removed the hierarchy view from the documentation. With it it was easy to see all classes derived from a certain base class like Object, Collider, Renderer, ...
edit
Actually your first version is the more reliable one since if the GameObject holds multiple instances of the same component, only the first one is returned and that isn't necessarily the instance invoking GetComponent.
Well I feel foolish. I thought Destroy(this) would destroy the actual script. Thanks!
@$$anonymous$$: Uhm with "actual script" you mean the class itself? That's not possible since all classes are compiled into one (a few) DLL assembly files which can't be altered at runtime.
Destroy(this) will remove the script instances that is invoking that line.
It destroys the instance of the script. Not the actual script itself.
I got scared cuz I accidentally deleted a prefab once. Thanks for your help!!
Destroy shouldn't be able to touch assets. DestroyImmediate can.
Your answer
Follow this Question
Related Questions
How to safely destroy component with dependants? 2 Answers
Why does my bullet prefab get destroyed? 1 Answer
Destroy all scripts on object. 3 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
OnTriggerEnter - destroy (this.gameobject) if it collides with anything 2 Answers