- Home /
Destroy gameobject component that inherits from a certain class
I would like to destroy a gameobject script component that inherits from a certain parent class (CharacterInput), I have tried this:
Destroy(gameObject.GetComponent(typeof(CharacterInput)));
But it does not destroy the script that inherits from CharacterInput. Any help would be much appreciated.
Answer by Bunny83 · Jun 07, 2020 at 03:01 PM
Your code should work just fine. If it doesn't for you you might have some other error in your setup. First of all are you sure the component is attached to the same gameobject that the script with that line of code is attached to? Keep in mind that GetComponent only gets components on that one single gameobject. If the "CharacterInput" derived script is attached to a child or the parent gameobject your code doesn't work. Also keep in mind that if there are several components on the same gameobject which fullfill this condition, only one of them will be returned and destroyed.
All you mentioned is that "it doesn't work". However do you get any errors instead? What have you already done to debug your issue? Have you checked what GetComponent actually returns? Are you sure you are executing this code on the correct gameobject? A common error is to execute code on a prefab instead of the actual instance in the scene. All those things are unknown to us and therefore we can't be more specific in our answers.
ps: regardless of your actual issue, you can also use the generic version of GetComponent: In addition you might want to add some safety checks
var comp = gameObject.GetComponent<CharacterInput>();
if (comp != null)
Destroy(comp);
else
Debug.LogWarning("Tried to destroy CharacterInput component, but none was found");
Thank you very much, the box collider I was interacting with was on a child gameObject of the one containing the script. I should have thought about debugging the gameObject it was accessing, my bad.
Answer by GREYSETH · Jun 07, 2020 at 02:36 PM
@TheGodling You should make the CharacterInput component into a variable
Example : CharacterInput input = GetComponent(typeof(CharacterInput)); Destroy (input);
Or you can simply disable the component
Example :
GetComponent<CharacterInput>().enabled = false;
Answer by Roger_0123 · Jun 07, 2020 at 01:29 PM
I don't understand, you want to destroy a component (and not the entire gameObject) of a gameObject with CharacterInput component? Or do you mean that your script component inherits from class CharachterInput?
I meant that that there is a gameobject who has a script component that is a class that inherits from the CharacterInput class. I want to remove that script component from the gameObject.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Trouble with destroy function 2 Answers