-
Notifications
You must be signed in to change notification settings - Fork 134
Avoid usage of Find methods in performance critical context
Unity provides a number of methods to find other game objects, components and transforms. These are usually found by name, or tag or type, and the lookup cost can be very high. These methods should be avoided inside a performance critical context:
Transform.Find
GameObject.Find
GameObject.FindGameObjectWithTag
GameObject.FindGameObjectsWithTag
GameObject.FindWithTag
Object.FindObjectOfType
Object.FindObjectsOfType
Object.FindObjectsOfTypeIncludingAssets
Resources.FindObjectsOfTypeAll
This inspection will add a performance indicator highlight to each method call, when made inside a performance critical context. It will also mark the calling method as expensive, and any usages of the calling method will also receive a performance indicator highlight.
The inspection also adds Alt+Enter context actions to move the find method call to Start
or Awake
, introducing a field to cache the return value. Please be aware that this can change the semantics of your code, as the object will be found at a different time, and will not be updated as your game progresses.
Care should also be taken to avoid a null check followed by a find, as this can result in searching every frame for something that does not exist.
This inspection was first added in Rider/ReSharper 2018.3