Search Unity

Feedback Avoid FindObjectWithTag in Camera.main

Discussion in 'Editor & General Support' started by Peter77, Feb 22, 2020.

  1. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,609
    What have several Unite talks, the Unity documentation and Unity learning materials in common?
    They tell us "Accessing Camera.main is expensive".

    For example, I'm currently reading this document and came across the same statement again:
    upload_2020-2-22_20-22-42.png

    My feedback is: Just fix it! Make it fast! Return a cached reference when accessing Camera.main instead, like you describe yourself in the "Solution".

    Bonus points for adding a "mainCameraChange(oldCamera, newCamera)" event that allows to receive a notification when the main camera was changed.
     
    Last edited: Feb 22, 2020
    jamespaterson likes this.
  2. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    The purpose of Camera.main is to return something that "just works". A cached solution would introduce edge cases. If you're doing something where you care about the performance of Camera.main and/or you're doing something complicated enough to where Camera.main is not the best solution, then you won't be using Camera.main anyway. A more complicated or comprehensive system in my opinion would necessarily create too many assumptions about the use-case of the user. For example, there's a reason that Cinemachine is a plugin and not the required built-in way to manage cameras.

    There's no incentive to make Camera.main faster since anyone who cares is not using it.


    EDIT: The above is no longer relevant, as the performance issues of Camera.main have been fixed as of 2019.4.9.
     
    Last edited: Aug 10, 2020
  3. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,609
    If you look at Unity's source code, such as the UI, you'll find Camera.main is used in their code / hot-paths.
     
    Last edited: Feb 23, 2020
    Ghat-Smith and jamespaterson like this.
  4. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,609
    fyi: This has been fixed in Unity 2020.2.0a16. :) Not sure if the fix gets backported to LTS.
    @richardkettlewell
     
  5. richardkettlewell

    richardkettlewell

    Unity Technologies

    Joined:
    Sep 9, 2015
    Posts:
    2,285
    There is and we did :)

    Peter, we backported it to 2020.1 so far. I was waiting for a month or so, to see if any bugs came out of it, before having a conversation internally about whether to backport it to 2019.4. It’s probably been about a month now...
     
    Madgvox, SINePrime and Peter77 like this.
  6. richardkettlewell

    richardkettlewell

    Unity Technologies

    Joined:
    Sep 9, 2015
    Posts:
    2,285
    It just landed in 2019.4.9!
     
    Peter77, BABIA_GameStudio and Madgvox like this.