It’s not an issue in this project, but in prior projects (albeit probably because of less than ideal coding) I’d sometimes have async issues with components not existing yet. So I’d have to GetComponent during runtime etc. But I’ve heard GetComponets can be very resource-intensive. But is it really only a big deal if running it inside Update()? Just wondering what “best” practices may be.
Hi Stephen, good question.
My understanding is for something that is resource-intensive the idea is just to reduce the number of times that it is called. The advantage of calling it in start or awake is that you can store the reference to the GameObject early on and you will have it for later. This can also prevent several different scripts from calling GetComponent at the same time (during runtime) inadvertently, and taxing your resources. It’s certainly inevitable that you will at some point have to call it during runtime. In this case the idea is just to avoid calling it every frame or for no reason.
So this is really an optimization problem that depends on your game structure. Since GetCompoent is iterating over all the components in an object, the more components you have and the more objects this it is being called on, the more resource intensive it will be. So the best practice is just to store that reference and reduce the number of unnecessary iterations. The same way you would avoid looping through any data structure and minimizing searches to improve efficiency. Hope this helps.
Ah, that is a good way of looking at it. Nice ‘clicking’ moment for me. Thanks for the good explanation!
This topic was automatically closed after 14 days. New replies are no longer allowed.