-
Notifications
You must be signed in to change notification settings - Fork 140
Avoid usage of GetComponent methods in performance critical context
The various different GetComponent methods will return a component attached to the GameObject, if available. This lookup will return all components, or filter by type, and can walk the transform hierarchy. These methods can allocate memory, and have a high lookup cost, and should be avoided inside a performance critical context or risk per-frame allocations and poor performance.
GameObject.GetComponentGameObject.GetComponentsGameObject.GetComponentsInParentComponent.GetComponentComponent.GetComponentsComponent.GetComponentInChildrenComponent.GetComponentInParentComponent.GetComponentsInChildren
It is recommended to move the call to Start and cache the results, or to use a direct reference. Some functions such as GameObject.GetComponentsInChildren allow for providing a list to store results, which can remove the per-frame allocations, but the performance of lookup is still high, so only use this if lookup is unavoidable.
This inspection will add a performance indicator highlight to a method call inside a performance critical context. It will also provide Alt+Enter context actions to move the call to Start or Awake and introduce a field to hold the cached result.
This inspection was first added in Rider/ReSharper 2018.3