Caching components vs GetComponent<T>() (in RPG course)

I am following the Core RPG course (which I am loving btw) and I have noticed that Sam uses GetComponent().anyFunction() directly and even sometimes its used in the main loop (Update).
I was curious if this gets refactored later on but by checking out the final code in the repository it seems that’s not the case.

This raised some questions and confusion in my head:

  1. Is Sam wrong for doing so and it is just something overlooked or is there some reason behind this that i simply lack the knowledge to understand. If that’s the case please elaborate.

  2. I’m I being unnecessarily cautious all this time about the performance issues that this might cause? Is it unnecessary to cache the components in variable on awake or start even when they are going to be used in the main loop?

You’re quite right, we don’t get much into caching components. I will say that in a small project, with not a lot of things going on, this isn’t actually a big problem. If you build out your game and have very large levels with say 2 or 3 hundred characters, it could begin to affect performance.

That being said, it’s a good habit to get into. I prefer to cache my components that are attached to the same GameObject in Awake().

1 Like

Thank you for your reply it really clears things up and gave me more understanding of the scale on how much GetComponent search can affect performance. Caching is not important for the scope of the tutorial project so Sam doesn’t bother with it which even helps the code stay a bit cleaner.

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