gameObject.GetComponent vs GetComponent

In a script I got a reference to an object’s sprite renderer with the code

renderer = gameObject.GetComponent();

This gave me a C# warning CS0108, hides inherited member. I get rid of this warning, however, when I change the code to:

renderer = GetComponent();

In the same script, I use gameObject.GetComponent in order to get a reference to the Animator that is a child of this game object.

How can I tell the difference when I should be using gameObject vs not using gameObject?

Ok so:

Every script you write in Unity inherits from MonoBehaviour.Unity - Scripting API: MonoBehaviour

MonoBehaviour extends from Component Unity - Scripting API: Component

Component has a method called GetComponent: Unity - Scripting API: Component.GetComponent

However the GetComponent on Component really just proxies to GetComponent on GameObject as we can see in the Unity source code: UnityCsReference/Runtime/Export/Scripting/Component.bindings.cs at 61f92bd79ae862c4465d35270f9d1d57befd1761 · Unity-Technologies/UnityCsReference · GitHub

In other words:

myComponent.GetComponent is basically just a shortcut way of saying myComponent.gameObject.GetComponent. There is no real difference between them, and you should prefer the shorter version for brevity.

As for your C# warning CS0108, it has nothing to do with how you’re calling GetComponent, and it has everything to do with the fact that you have a field/property called “renderer” which hides a property on Component called “renderer”: UnityCsReference/Runtime/Export/Scripting/Component.deprecated.cs at 61f92bd79ae862c4465d35270f9d1d57befd1761 · Unity-Technologies/UnityCsReference · GitHub

8 Likes

AH, ok, I understand the difference now, and I understand where the warning came from.

Thank you for the detailed response, I appreciate it.

Thank you very much! This really clarifies the confusion I’ve been having why GetComponent appears both in Component and GameObject