Search Unity

Is GetCompnent necessary?

Discussion in 'Getting Started' started by LumoKvin, Mar 20, 2020.

  1. LumoKvin

    LumoKvin

    Joined:
    Sep 28, 2019
    Posts:
    195
    What is the difference between this:
    Code (CSharp):
    1. public class Example : MonoBehaviour
    2. {
    3.     Image m_Image;
    4.     public Sprite m_Sprite;
    5.  
    6.     void Start()
    7.     {
    8.         m_Image = GetComponent<Image>();
    9.         m_Image.sprite = m_Sprite;
    10.     }
    and this:
    Code (CSharp):
    1. public class Example : MonoBehaviour
    2. {
    3.     Image m_Image;
    4.     public Sprite m_Sprite;
    5.  
    6.     void Start()
    7.     {
    8.         m_Image.sprite = m_Sprite;
    9.     }
    Why do we need to use GetComponent? I always see this in the documentation but it seems to work fine without it.
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    The difference is, the second one will not work. It will raise a NilObjectException as soon as the script starts.

    m_Image is a private property, and (like all such) its value is nil until you assign some other value to it. GetComponent is one way to get such a value to assign.
     
  3. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,157
    You need it because the game engine doesn't automatically populate the field with a reference to the component, and there is no way to populate it automatically because there is no way for the game engine to know the intentions of the developer.

    You could in theory write an attribute that informs the game engine of your intentions, but you wouldn't gain anything from it because you'd just be shifting a one-line instruction from one position to another in the script. If you had additional code that needed to be executed that'd be different but you don't in your examples.
     
    Last edited: Mar 20, 2020
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    If you set m_Image as public you could populate it via drag/drop in the inspector to avoid using GetComponent. Otherwise what everyone else said.
     
    JoeStrout likes this.