Get a mouse object click

Hi,

I have some problem getting the mouse to work, I want to click on an object to turn on/off the game. But I can’t is giving me this NullReferenceException: Object reference not set to an instance of an object. I have no idea why, this is just a test.
using UnityEngine;
using System.Collections;

public class OnOff : MonoBehaviour {

	public bool on = false;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {

		RaycastHit2D hit = Physics2D.Raycast(Input.mousePosition, Vector2.zero);

		if(hit != null) {

			if(hit.collider.gameObject.name == "On") {

			Debug.Log( "faucet");
			
			}
		}

			

	}
}

I’m a beginner, any help? Thanks. Is c#.

I ran into this issue. I don’t know if issue is a bug or if I’m missing something, but a workaround is to check for the existence of the collider as well:

 if(hit != null && hit.collider != null)

Note this gets rid of the null reference, but you are not detecting a click. Take a look at Input.GetMouseButtonDown(). You will put your raycast inside of a:

if (Input.GetMouseButttonDown(0)) {
  // Existing raycast code goes here
}