- Home /
Quick GetComponent syntax problem!
Hello! A little line of code isn't behaving as expected! Likely a noob problem?
this.transform.parent.GetComponent<COMPONNEEENNT>.RunThisMethod();
Ok, that works. But this...
Component component;
component = this.transform.parent.GetComponent<COMPONNEEENNT>();
component.RunThisMethod();
Yeah, that doesn't work. Whyyyy...
"Type `UnityEngine.Component' does not contain a definition for 'RunThisMethod'..."
Answer by Bunny83 · Jul 08, 2013 at 12:23 AM
C# is a strongly types language. So each variable has a certain type. You declared your variable of type Component. component is the base-class for all components, but this class of course doesn't have any of the specialized functions of variables you have defined in your sub class.
You should declare your variable like this:
COMPONNEEENNT component;
component = transform.parent.GetComponent<COMPONNEEENNT>();
component.RunThisMethod();
Or as alternative use a type-inferred variable like this:
var component = transform.parent.GetComponent<COMPONNEEENNT>();
component.RunThisMethod();
type-inference only works for local variables. Member variables of the script always need a concrete type.
ps: Your first version won't work since you're missing the calling brackets of Getcomponent. It should look like this:
transform.parent.GetComponent<COMPONNEEENNT>().RunThisMethod();
Thanks for the very complete answer! Everything's running well now and you explained the theory behind the fix too c:
Also thanks for catching those missing brackets
Answer by Oribow · Jul 08, 2013 at 12:04 AM
Write the Script name and not Component to declare the variable.
$$anonymous$$aybe I'm not understanding the way you word your answer. $$anonymous$$gested solution,
Component component;
component = this.transform.parent.GetComponent("CO$$anonymous$$PONNEEENNT");
component.RunThis$$anonymous$$ethod();
does not resolve the problem.
Your answer
![](https://koobas.hobune.stream/wayback/20220613105643im_/https://answers.unity.com/themes/thub/images/avi.jpg)