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?
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;
}
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 usesFindGameObjectsWithTag
internally and doesn't cache the result. It is advised to cache the return value ofCamera.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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With