Skip to content

Camera.main is inefficient in frequently called methods

Matt Ellis edited this page Mar 14, 2022 · 15 revisions

The Camera.main property returns the first camera that is tagged with "MainCamera". For Unity versions earlier to 2019.4.9, this is implemented by calling FindGameObjectsWithTag. The result is not cached, so accessing this property frequently can have an impact on performance. Consider caching the camera in a field, and setting the value in Start or Awake.

Since Unity 2019.4.9, Camera.main is now much faster. Internally, Unity maintains a cache of GameObject instances that have the "MainCamera" tag, and Camera.main will return the first enabled object in this cache. While this is much faster, it is now similar to calling GetComponent (including the transition to native code), and is still advisable to cache the value. Note that this highlight can be disabled in Preferences | Editor | Inspections | C# | Unity Performance Inspections.

This inspection will add a performance indicator highlight to the Camera.main property when it is accessed in a performance critical context. The inpection also provide context actions via Alt+Enter to cache the result in Awake or Start method.

See the documentation for Camera.main and also the support document "Camera.main is slow". The release notes to Unity 2019.4.9 simply state: "Camera.main is much faster to query". This blog post on performance improvements in Unity 2020.2 includes a section on "Optimised Camera.main".

History:

  • This inspection was converted into a performance indicator in Rider/ReSharper 2018.3
  • This inspection was first added in Rider/ReSharper 2018.2
Clone this wiki locally