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’…”

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();

Write the Script name and not Component to declare the variable.