'Object reference not set to an instance of an object Crosshair.OnGUI ()

Hello developers I am Ravi Singh Chauhan I get error taht says:- NullReferenceException: Object reference not set to an instance of an object Crosshair.OnGUI () (at Assets/Scripts/Combat/Crosshair.cs:22) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

My Crosshair script is here:- https://i.stack.imgur.com/hD2NE.jpg

Please help me to solve this error



Solution 1:[1]

Since the script is inheriting MonoBehaviour, I don't think transform can be null, so then I'm assuming it must be that the camera is null. From the documentation:

The first enabled Camera component that is tagged "MainCamera" (Read Only).

If there is no enabled Camera component with the "MainCamera" tag, this property is null.

You should be able to cache the reference here for one, and that would also help you see if the camera is null or not. It could be that your main camera is disabled or you've deleted the main camera, added a new camera, and then didn't tag the new camera.

You posted a picture of your code instead of the code itself and I'm not going to rewrite your code myself, so instead I'll just say you should try making a private Camera, tag it with [SerializeField] so you can see it in the editor, assign the Camera.main to that on Start, and then see if it's empty or populated when you run the game. Use your cached Camera instead of doing the lookup every call (unless you're planning on switching cameras a lot or something).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chuck