Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

gameObject.GetComponent vs GetComponent

Discussion in 'Scripting' started by rogue_moravec, Aug 8, 2020.

  1. rogue_moravec

    rogue_moravec

    Joined:
    Mar 6, 2020
    Posts:
    4
    In a script I got a reference to an object's sprite renderer with the code

    renderer = gameObject.GetComponent<SpriteRenderer>();

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

    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?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Ok so:

    Every script you write in Unity inherits from MonoBehaviour.https://docs.unity3d.com/ScriptReference/MonoBehaviour.html

    MonoBehaviour extends from Component https://docs.unity3d.com/ScriptReference/Component.html

    Component has a method called GetComponent: https://docs.unity3d.com/ScriptReference/Component.GetComponent.html

    However the GetComponent on Component really just proxies to GetComponent on GameObject as we can see in the Unity source code: https://github.com/Unity-Technologi...me/Export/Scripting/Component.bindings.cs#L35

    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": https://github.com/Unity-Technologi.../Export/Scripting/Component.deprecated.cs#L55
     
    Last edited: Aug 2, 2022
  3. rogue_moravec

    rogue_moravec

    Joined:
    Mar 6, 2020
    Posts:
    4
    AH, ok, I understand the difference now, and I understand where the warning came from.

    Thank you for the detailed response, I appreciate it.
     
  4. xidingart

    xidingart

    Joined:
    Jan 14, 2022
    Posts:
    1
    Thank you very much! This really clarifies the confusion I've been having why GetComponent appears both in Component and GameObject