OnMouseDown, Raycast, Error

Hello here i have a part of a script that reads, if i press on the gameobject then a boolean will be activated and an object will be activated, but if i click outside of the gameobject then the boolean will be set to false, and the object will be set to false, but i get this error when i click on the gameobject:

NullReferenceException: Object reference not set to an instance of an object
worker_Controller.OnMouseDown () (at Assets/Scripts/worker_Controller.js:21)

Any ideas? Thanks :slight_smile:
here is my code:

function OnMouseDown ()
    {
        var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        var hit : RaycastHit;
     
        if (Physics.Raycast(ray) && hit.transform.gameObject == "Worker")
        {
          Selected = true;
          SelectedRing.SetActive(true);
        }
        else
        {
         Selected = false;
         SelectedRing.SetActive(false);
     	}
     
    }

This is hard to troubleshoot without knowing the full setup of your scene: is the above script attached to the object you want to select? Theoretically you won’t need to fire a Raycast as the OnMouseDown has already detected a click on the object in question.

Also, your check of hit.transform.gameObject == "Worker" will return false. Perhaps you mean hit.transform.gameObject.name == "Worker" or hit.transform.gameObject.tag == "Worker"?

Your hit variable is never assigned to so it will always remain null. You should use “Physics.Raycast(ray, out hit);” instead.

function OnMouseDown () {
	var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	var hit : RaycastHit;

 	if (Physics.Raycast(ray, out hit) && hit.transform.gameObject == "Worker") {
		Selected = true;
		SelectedRing.SetActive(true);
	}
	else {
		Selected = false;
		SelectedRing.SetActive(false);
	}
}

You simply need to have a collider on that object. Without one theres nothing for the raycast to collide with and check in with the bool if it did.

You will need to add it in the inspector or you can do it through code if your doing it on runtime.

SelectedRing.AddComponent();

You can use other colliders as well such as MeshCollider, SphereCollider etc.