Why Explicitly Set References?

Is there a specific reason why we’re explicitly setting references for things like the Unit Selection Handler when the script exists on the same object? In other courses we typically use GetComponent to create a reference in the Awake hook. It seems as though there is likely a greater chance at misconfiguration through the GUI than if you were to use the annotation [RequireComponent(UnitSelectionHandler)] and then retrieve the reference in Awake. Is there a particular advantage or is this more of a personal style kind of thing?

Why is almost always answered by “That’s what the developer was thinking at the time”

As you can see, there are many ways to do it. Every way has its downside and upside.

Hi there, good question. This situation mostly comes down to preference. I personally find it annoying to drag and drop all my references, and prefer use to GetComponent. Especially if I think I’m going to reuse the script on another object, then setting up all those references could get irksome.
However it is a fast way to set a preference. As well, this means the object has the reference already and does not have to search the gameObject for it. This could theoretically have a performance bump when loading the scene. However, you would be probably need tons of getComponents before you notice it taking more time to get through the awake method.

I use drag and drop from editor - rather than GetComponent in the Awake method - purely for performance considerations… these things do (surprisingly) add up very quickly.

As a programmer, I try to avoid using the editor as much as possible and rely in having things set up in code but, again, in this particular situation, because of the performance consideration, I drag/drop from the editor.

… may not matter if you do games for fun/hobby, but as I write commercial games on a professional basis - games that have to be performant - it matters to me

1 Like

Cool, that is interesting to hear. I can see how those getComponent calls can add up quickly.

Privacy & Terms