Quick question about GetComponent() perfromance in Health script

A quick question about GetComponent(), I’ve been revisiting my learning and came across this video (looks like Unity official tutorial) saying GetComponent is expensive and should be called infrequently at 2:47; however in our Health script, GetComponent() has been called many times in everywhere and sometimes in Update() call related. Just wondering is this a matter we should be considered now or in a later stage when refactoring, or it is not an issue in terms of performance. Than you.

For prototyping a game, it’s ok to use GetComponent liberally, but yes, eventually these references will need to be cached. At least some of the references.
Here’s my general rule of thumb:

  • Always cache components attached to the same GameObject that you know will always be there. (Mover, Fighter, Animator, etc). Ideally your script should include a [RequireComponent] tag for each class. Once they are cached (preferably in Awake), you shouldn’t need to constantly null check them.
  • Sometimes cache components on another GameObject, but those references must be null checked before acting on them
  • Never cache state, these should always be calculated.
3 Likes

Thank you Brain for sharing your valuable knowledge. I’ve just tried your suggestions to refactor this Health script, they worked very well. Really learned a lot from all your previous comments to different students. Thanks a lot.

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

Privacy & Terms