Caching Camera.Main for better performance

When starting a host game, I notice that in our Player aiming logic we get the mouse position on screen by calling Camera.main.ScreenToWorldPoint();

Would it be possible to assign the Camera to a variable to cache it in memory rather than calling it on every LateUpdate? I know calling Camera.main can be an expensive operation.

Currently doing something like:

private Camera mainCamera;

void Start(){
      mainCamera = Camera.main;
}

    private void RotateTurret(){
        if (!IsOwner) { return; }
        
        Vector2 turretPosition = inputReader.MousePosition;
        Vector2 mousepositionOnScreen = mainCamera.ScreenToWorldPoint(turretPosition);

        turretTransform.up = new Vector2(
            mousepositionOnScreen.x - turretTransform.position.x,
            mousepositionOnScreen.y - turretTransform.position.y
        );
    }

will cause a null reference exception when attempting to host a game with the error showing that the Camera has been destroyed but that the script is still trying to access it.

It’s not really. It used to be in older versions of Unity, but it’s getting cached by Unity already now. However, the documentation does recommend you cache it yourself if needed. I don’t think it’s needed in a small project like this

Hi tastydew,

Welcome to our community! :slight_smile:

I assume you already tested your code. And I also assume that your code worked. So the answer is: Yes, it is possible to cache the reference. :wink:

bixarrio is right. Camera.main is not as expensive anymore as it used to be. According to the API, ‘[a] accessing this property has a small CPU overhead, comparable to calling GameObject.GetComponent’.

In a little game like ours, it does not matter much but, personally, I would cache the Camera object like you did. With just two lines of code, you won’t have to worry about it anymore if your game becomes bigger.


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms