Avoid FindGameObjectWithTag and GetComponent

You can cache the result on a field on Awake just once, instead of executing these expensive methods every time you call RedrawUI.
Or even better, just serialize the script component and assign it from the inspector.

1 Like

All good points and things to know. However sometimes these are not possible or sufficient.

Serializing the field isn’t always possible because prefabs cannot have references to something in the hierarchy, for example. Only once it has been instantiated into the hierarchy itself can it get that reference. Sometimes you may add a component in code, so it didn’t exist at design time but it does now at run time.

In some cases a reference may change, so caching it in awake would not be sufficient, because you’ll get a reference to the current object, but if it changes you need to get a new, fresh reference.

Yes, these calls are expensive, but they’re not nearly as expensive as you may think. A lot of games - and I mean popular commercial games - use it without issue. But your advice is gold. If it is possible, try to avoid calling these too often.

1 Like

Privacy & Terms