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
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;
}
}
}
}
}