Faster than camera.main ?

I was looking for an alternative to camera.main / camera.current and since I’m using cinemachine throughout I thought I would write this function.

  public static CinemachineBrain GetActiveBrain()
        {
            CinemachineBrain brain = null;
            if (CinemachineCore.Instance != null)
            {
                if(CinemachineCore.Instance.BrainCount > 0)
                {
                    brain = CinemachineCore.Instance.GetActiveBrain(0);
                }
            }
            return brain;
        }

Is this faster? recommended?

Your question is a bit vague. :frowning: Could you clarify?

Is it faster than what?

Why do want to have this function?

from your own site https://support.unity3d.com/hc/en-us/articles/115000227183-Camera-main-is-slow

I still don’t understand your question.

Is getting an active brain faster than getting camera.main?

sorry I suppose I should repeat the title question in the body of the post.

So yes, is using GetActiveBrain faster than camera.main?

As for the use case, I have several scenes in my game with their own camera brains that get loaded and unloaded all the time. As a result, I wanted to quick way to get the active camera. Caching camera.main on awake() doesn’t always work because the camera brain changes during play.

I’m also using it to issue blending started and blending ended custom events by constantly polling brain.IsBlending

In my game I have an extensive need to know when camera blending has started and ended. To this end, I created the following script.

public class CameraBrainBlendingEvents : MonoBehaviour
    {
        private bool BlendingStarted = false;
     
        public void Update()
        {
            CinemachineVirtualCameraBase activeCamera = CinemachineHelpers.GetActiveVCam(); 

            if (activeCamera == null) return;

            CinemachineBrain brain = CinemachineHelpers.GetActiveBrain(); 
    
            if (brain != null && BlendingStarted == false && brain.IsBlending)  // detect if blending has started
            {
                BlendingStarted = true;
         
                EventCommand.Camera.CameraBlendingStarted(activeCamera);  // my custom event 
            }
            else if (brain != null && BlendingStarted == true && !brain.IsBlending)  // detect if blending has ended
            {
                BlendingStarted = false;
           
                EventCommand.Camera.CameraBlendingEnded(activeCamera); // my custom event 
            }
        }
     
    }

Would it be possible to add something like this to Cinemachine?

1 Like

Your GetActiveBrain function is about 2-3 times faster than getting camera.main (in my tests).

Probably yes, I’ll add it as a feature request :wink:

ok well that’s fantastic. I just wanted to make sure there wasn’t some unknown gotcha hiding inside CinemachineCore.Instance.GetActiveBrain(0)

1 Like