Is "Camera.main" being cached?

Heya,

just came across a couple of tweets stating that “Camera.main” is pretty much just called “FindObjectWithTag” every time you call it.

Curious if anyone knows for sure if this is the case or if it’s being cached as well.

Thanks!

I doubt it since you can change the main camera at any time.

Best to manage it yourself.

1 Like

This.

The only thing Unity can reliably cache is Component.transfrom and Component.gameObject as these values never change.

Anything that can be changed can’t be cached effectively.

Just be a control freak, like any good programmer and you’ll go a long way.

3 Likes

Here’s the actual property, so at the very least it looks like it calls into the C++ part of the engine

/// <summary>
///   <para>The first enabled camera tagged "MainCamera" (Read Only).</para>
/// </summary>
public static extern Camera main { [GeneratedByOldBindingsGenerator, MethodImpl(MethodImplOptions.InternalCall)] get; }

Just saw this on Twitter, and thought of this thread (this is the Twitter of Matt Schell, who does a lot of the official Unity tutorials):
Matt Mirrorfish‏ @MattMirrorFish 10m10 minutes ago
I wondered why using Camera.main was so slow… From Ian Dundore’s excellent @unity3d performance talk. https://www.youtube.com/watch?v=_wxitgdx-UI&t=484s … #unitytips pic.twitter.com/Y8DXz0H8MY

For those that can’t see the pic…

Camera.main…
Calls Object.FindObjectWithTag(“MainCamera”)
Every single time you access it.

4 Likes

Camera.main has been improved in Unity 2020.2: Unity Blog

2 Likes

It’s still more efficient to cache it. That advice is just for the lazy or prototypes.

3 Likes