Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What alternatives are for Camera.main?

Tags:

unity3d

Everywhere I see that using Camera.main is a bad practice and that we shouldn't use it. So what is the good practice to get the main camera object?

like image 867
J.Horcasitas Avatar asked May 24 '20 22:05

J.Horcasitas


2 Answers

You should store a reference to each of your Cameras once in the lifetime of that Camera, and then use that stored reference in the rest of the code. For example:

// Reference initialization
public Camera mainCamera;

// Game code, executed once per frame or more
void Update()
{
    Vector3 pos = mainCamera.transform.position;
}
like image 105
Hamid Yusifli Avatar answered Nov 15 '22 10:11

Hamid Yusifli


Camera.main is basically kind of the same as using FindGameObjectsWithTag("MainCamera") and thus quite expensive.

The primary Camera in the Scene. Returns null if there is no such camera in the Scene. This property uses FindGameObjectsWithTag internally and doesn't cache the result. It is advised to cache the return value of Camera.main if it is used multiple times per frame.

The DON'T USE IT actually refers to a usage every frame.

There is nothing bad about it if you use it only once:

// Best is always if you can reference things already via the Inspector
[SerializeField] private Camera _camera;

private void Awake()
{
    // As a FALLBACK get it ONCE e.g. in prefabs where you can't reference
    // the scene camera
    if(!_camera) _camera = Camera.main;
}
like image 26
derHugo Avatar answered Nov 15 '22 11:11

derHugo