Camera.current null Reference

Hello, i have this following code, which should print out the name of the game object being hit on mouse button down… except it is giving me anullreference exception for every thing… the error of the null reference is occuring on the Ray ray = camera.current; why is this null?

but when i say print(Camera.current.tag); (in the update)
it is not null…

if(Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.current.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if(Physics.Raycast(ray, out hit, 100))
            {
            Debug.Log(hit.transform.gameObject.name);
            }
}

btw what i am trying to do is simply get the name of the UI element which is being clicked on in the canvas… but this is difficult since it is an image, and if i use the line of code:

EventSystem.current.currentSelectedObject

it also returns a nullrefernce since the object is an image and not a slider or something like that…

There’s your problem. Update isn’t called while a camera is rendering, so there is no “current” camera. Check out the docs for Camera.current; it’s only valid during the actual render process.
You may want Camera.main instead, which will give you the Camera which is tagged with the MainCamera tag?

2 Likes

is there a way to get another camera. because i have 2 cameras, one main and one not, i would like to switch on demand, so the raycast works well, camera.main seems to be a little less dynamic

i think the answer is in the docs of camera.main…

thanks