C# NullReferenceException Point and Click Game

Hello,

I need some help with error handling. I have a NullRefenceException error. I am trying to code the movement between rooms in a point and click game. The problem is that when I click outside the area to where I want to move to, nothing is supposed to happen however I get this error NullReferenceException: Object reference not set to an instance of an object
ClickedObject.Update () (at Assets/Custom Assets/scripts/ClickedObject.cs:35).

I need something like if object is null, do nothing. Any advice would be much appreciated :slight_smile:

Here is my code so far:

using UnityEngine;
using System.Collections;

public class ClickedObject : MonoBehaviour 
{
	private Camera camera;
	public GameObject clickedObj;
	public float speed = 10.0f;
	private bool startMove;
	private Vector3 myPos;


void Start()
	{
		camera = Camera.main;
	}

	// Use this for initialization
void Update()
	{
		 myPos = transform.position;
		// Debug.Log(myPos);

		RaycastHit hit;
		Ray ray = camera.ScreenPointToRay(Input.mousePosition);


			if (Input.GetMouseButtonDown (0))
				{	
				
				if (Physics.Raycast(ray,out hit)); 
					{
						//Debug.Log ("Object is hit" );

						clickedObj = hit.collider.gameObject;
						//Debug.Log(moveToObj);
				if (clickedObj.tag == "goTo")
				{
						startMove = true;
				
				}
						//Debug.Log(moveToObj.transform.position);


					}

				}



				if (startMove)
					{

			if (transform.position != clickedObj.transform.position)
						{
					
				transform.position = Vector3.MoveTowards(myPos, clickedObj.transform.position, speed*Time.deltaTime);


				if (transform.position == clickedObj.transform.position)
							{
								startMove = false;
							}

						}
					}
		}
	}

First of all, please learn how to use code tags:

http://forum.unity3d.com/threads/143875-Using-code-tags-properly

Secondly, you have a logical error in your code;

if (Physics.Raycast(ray,out hit));

I’m not sure if this should even compile, but I guess it does. That semicolon ends the if statement right there.

Finally you can always check if “hit” is null or not, something like this:

if ( hit != null ) {
    // Something got hit
}

Hope this helps!

Thank you for pointing out the logic error. All good now. Although ’ if (clickedObj != null) ’ worked better in this case. I had errors with checking hit.

Additionally to what toreau has already mentioned, you might wanna make sure that you have a camera attached to the gameObject or use Camera.main instead of camera, because latter one will try to access a the camera component on your gameObject the script is attached to.

Also, you can put the code

RaycastHit hit;
Ray ray = Camera.current.ScreenPointToRay(Input.mousePosition);

into your if statement because you only need that when you really click with mousebutton 0.