Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

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:
    4,995
    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:
    871
    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.
     
  3. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    4,995
    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:
    4,995
    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:
    1,587
    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.
unityunity