How to catch a NullReferenceException ?

Hello

I can think of other ways to fix this issue, but I wanted some input. The object I’m intending to hit has a collider attached, but I want to be able to fire even when it isn’t there.

Is there a way around this Null reference without having to use an off screen plane or something for the ray to hit?

		Ray ray = new Ray ( transform.position, transform.forward * 100f); 
		RaycastHit hit;
		
		Debug.DrawRay (transform.position, transform.forward * 100, Color.green);
					
		if( Input.GetMouseButtonUp( 0 ) )
		{
			Physics.Raycast(ray, out hit);
			
			try
			{
				Destroy(hit.collider.gameObject);
			}
			catch ( MissingReferenceException e )
			{
				Debug.Log(e.Message);
			}
		}

I also tried :

			if ( hit.collider.gameObject != null )
				Debug.Log("Test");

Both give me a null referece for the hit.collider.gameobject line.

Thanks

@T27M

Read it all before you conclude it.

I see that there’s an accepted answer. But, there is a better answer for handling NullReferenceExcep[tion. If you can relate programming in Java language like me, you can prevent from sending a null error by using the try-catch block. Try it for yourself! :wink:

If you’re using in C#, check if you have using System; at the top of your script file. If not, add it. Now, you can use all sorts of Exception classes while try-catching a line of code.

Here’s an example:

using System; // --> This exact line of code. That's it.
using UnityEngine;

public class Test : MonoBehaviour {

	public GameObject player; // --> Example to check if there's a null content;

	public void Update() {

		// You may now catch null reference here.
		try {

			player.transform.Translate(0, 0, 2);

		} catch(NullReferenceException e) {

		}

	}

}

Also remember, you can catch also other exceptions such as MissingReferenceException, MissingComponentException, IndexOutOfRangeException, or any other exception classes as long as you include using System in your script. That is all.

I see you checking for null, but you never check the base objects. This is what I mean (might be excessive, but give it a shot)

if ( hit != null && hit.collider != null && hit.collider.gameObject != null )
    Debug.Log("test");

Have C# 4.x?

if (!hit?.collider?.gameObject)
    Debug.Log("null");

I believe should work. The question mark checks for null (which you can do as long as whatever you’re doing accepts nullable). The “!” not checks for null as a bool.

A similar example with a callback:

Original:

if (callback != null)
  callback(true);

C# 4.x:

callback?.invoke(true);