Camera not being assigned to variable

I am attempting to access certain information from the main camera such as position and using screenToWorldPoint. Unfortunately, the debug log continues to return the message:

Attempting to work around the problem I decided to set the variable “mainCamera” using the code:

and then assigning the main camera to the variable in the user interface. Now it won’t let me select the main camera from the drop down menu next to the variable “mainCamera” even though it appears in the list. Assigning mainCamera by code doesn’t do anything either. Any help would be greatly appreciated.

For starters, it sounds like you’re trying to simply access ‘camera’ from a script on a game object that is not a camera, nor does it have the camera component attached, thus the error message. So as you’ve sorted the way to go about it (not a workaround, but the proper way) is to create a variable that references an in-scene camera. When doing that just declare the variable type as Camera, not UnityEngine.Camera. Try that and give it another go.

You can access your main camera, provided it has the “MainCamera” tag (which it does by default), with Camera.main. There’s no reason to assign the camera to a variable through the inspector or otherwise.

I changed the variable type to Camera but there was no change. I tried using the Camera.main but it continues to return the error when I use that. I checked and the only camera I have in the scene is tagged as the main camera. Is there another way I can access information on the camera? I have to know its position in order to perform some calculations necessary for my program. Thanks.

You’ve got something wrong in this project as Matthew and I are explaining how you go about this. Can you post a sample project perhaps? That way we can take a closer look. At a minimum, can you share your specific code?