Accessing GetComponent() without instantiating

Hi All,

I am experiencing problems on trying to figure out how this code works:

	UnityTalk respond;
	GameObject externalComponent;

	void Start () {
		externalComponent = GameObject.Find ("Directional Light");
		respond = GetComponent<UnityTalk>();
	}

So basically this is what I understand, GameObject is a class/constructor and Find is a static function, which means that it does not need to be instantiated. But then the problem starts at GetComponent. According to the docs, this is a public function. So how can this be accessed without being instantiated? I’m a bit confused here. Please help shed some light here.

GetComponent is a method for defined for the GameObject Class, and the method is not static, so you cannot do GameObject.GetComponent. Non Static Methods require an instance of the class type to be called, since you get the Component of type T from a gameobject, your code should be:

 void Start () {
         GameObject externalObject = GameObject.Find ("Directional Light");
         UnityTalk respond = externalObject.GetComponent<UnityTalk>();
     }

Hope this clarify a bit.

Any script inherits from components, so GetComponent() is in fact using Component.GetComponent() which fetches the component of the GameObject that the script is attached to.

if you dont specify which game object you want to get the component from, it is using the current gameObject that the monobehaviour is on. this is because getcomponent is a method in monobehaviour Unity - Scripting API: MonoBehaviour

GetComponent<XYZ>(); and gameObject.GetComponent<XYZ>(); will return the same results