GetComponent question

Hi! I love the course and have learned a lot from it even though I’m not really new to unity.
I did have a question, I notice GetComponent gets used quite a lot in methods during runtime for things that don’t really change.

Is there any reason for using GetComponent every time the method is called instead of getting whatever we need just once in Awake?

I have wonder this myself, I have no clue as to why Sam and Rick use GetComponent as much as they do, but here’s a great article that explains why you shouldn’t do that.

Thanks for the read, I honestly don’t really use getcomponent myself I almost always use SerializeField with private variables. However I’m following along with the courses making slight changes here and there and will refactor it once I finished the entirety of part 1.

Sam’s explanation on this is that in the prototyping stage, while you’re working up code, it’s ok to just pull the components as you need them.
I’m definitely more in the camp of GetCompnent() once, cache it for later. My rule is that if the component exists on the same GameObject as the component you’re working on, always cache it in Awake(). If it exists on a GameObject that’s being passed in an argument, then it may not always make sense to cache the component.


This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms