Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Get Components on same game object...

Discussion in 'Scripting' started by Rodolfo-Rubens, Aug 27, 2014.

  1. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    Why do we need to adopt this pratice, set the variables on the begining of the class and use GetComponent on Awake to fill these variables? Can't we just drag and drop the components on the variables and save some lines of code? If these variable must be private, can't we turn on debug mode and drop the Components there anyway, I mean, if it will be a prefab then those Components will always be the same, right? It's on the same GameObject...
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    You certainly can. Also - if the fields are private you can annotate them with SerializeField and they'll show up in the Inspector.
     
  3. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    Thanks! But also, sometimes you don't want a lot of fields on the inspector, but there is also this, thanks for the reply KelsoMRK.
     
  4. Limeoats

    Limeoats

    Joined:
    Aug 6, 2014
    Posts:
    104
    While the code becomes a bit more cluttered, it is also more readable in a sense. To programmers who do work outside of Unity, it is very strange to see a member of a class declared at the top, and then used without ever being initialized.
    By doing the initialization in the Awake method with GetComponent, it makes it a bit more clear that the variable is definitely initialized and ready to be used.
     
    Rodolfo-Rubens likes this.
  5. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    I find that working in a team of people, making sure stuff is assigned in the Inspector is kinda hard. Artists and level designers move stuff around, and sometimes references in the Inspector get removed causing a null reference to happen at runtime.

    If it's something that a level designer or artists might want to change, I'll make it public and have them set it in the inspector, then ALWAYS check for null. If it's something only me as a programmer will care about, I'll use GetComponent<>() in Awake() or Start() so that there's no possibility of someone else removing the reference in the Inspector.
     
    Last edited: Aug 27, 2014
    Rodolfo-Rubens and image28 like this.
  6. Rodolfo-Rubens

    Rodolfo-Rubens

    Joined:
    Nov 17, 2012
    Posts:
    1,197
    @Limeoats @Garth Smith Thanks for the replies guys! Now I understand, and it makes a lot of sense, I wasn't looking from this point of view. I will keep getting the components on the Awake() then...