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…
You certainly can. Also - if the fields are private you can annotate them with SerializeField and they’ll show up in the Inspector.
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.
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.
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.
@ @GarthSmith 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…