- Home /
When is current camera null?
I'm writing a UI system where I draw mesh's orthographically in worldspace and position them using the camera class.
Basically I get extreme points of the screen like so:
public static float CamRight
{
return RealCamera.ScreenToWorldPoint(new Vector3(Camera.current.pixelWidth,0,0)).x;
}
What I'm finding though is occasionally Camera.current is turning up null. I find this weird because it's null or not from the same place it's being called, so that means sometimes when it's called it's returning null and sometimes not but it's being called by the same instance of the same game object...
So I was just wondering if there were some rules I could follow for this?
Answer by CHPedersen · Oct 05, 2011 at 11:46 AM
Camera.current refers to the Camera that Unity is currently rendering things with. I can't tell you exactly why it turns up null, except this feeble guess:
Are you test-running your application in the editor with the sceneview displayed as well? Camera.current is not just your own application's camera, it is whatever is currently rendering, so sometimes, it actually refers to the editor's scene view camera. This camera will return null if you reference it without the scene view having focus, which is explained in this Question, also.
According to the docs, you should probably be using Camera.main, but that property returns whichever camera is tagged as the Main Camera. So if you need to refer to the camera that is currently actively rendering in your application, you need to keep track of them yourself.
I have the same functionality going in my application - to get around it I've simply declared a public static Camera variable in a static class. I set this variable whenever I change cameras, so it always refers to the camera I'm changing to.
Answer by Smurjo · Jun 12, 2021 at 09:36 AM
I had the same problem and observed: With only one camera in the scene Camera.current is null whereas Camera.main contains the camera (it is tagged main camera).
I think this is a suboptimal implementation from Unity, as I will need to change the code should I use more cameras in future.
Your answer
![](https://koobas.hobune.stream/wayback/20220612235405im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
the code of camera rig in tanks Game can explain how this works? 0 Answers
Problem with Camera rotation script 3 Answers