Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Is "Camera.main" being cached?

Discussion in 'Scripting' started by CaptainKiyaku, Jul 13, 2017.

  1. CaptainKiyaku

    CaptainKiyaku

    Joined:
    Feb 8, 2009
    Posts:
    324
    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!
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,384
    I doubt it since you can change the main camera at any time.

    Best to manage it yourself.
     
    Kiwasi likes this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    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.
     
  4. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    Just be a control freak, like any good programmer and you'll go a long way.
     
    Kurt-Dekker, ZO5KmUG6R and Kiwasi like this.
  5. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Here's the actual property, so at the very least it looks like it calls into the C++ part of the engine
    Code (csharp):
    1.  
    2. /// <summary>
    3. ///   <para>The first enabled camera tagged "MainCamera" (Read Only).</para>
    4. /// </summary>
    5. public static extern Camera main { [GeneratedByOldBindingsGenerator, MethodImpl(MethodImplOptions.InternalCall)] get; }
    6.  
     
  6. cstooch

    cstooch

    Joined:
    Apr 16, 2014
    Posts:
    354
    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.
     
  7. Eloren

    Eloren

    Joined:
    Jul 17, 2019
    Posts:
    20
  8. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    It's still more efficient to cache it. That advice is just for the lazy or prototypes.
     
    Bunny83, PraetorBlue and RadRedPanda like this.