How Do I Make Selecting Nothing OK?

Ok, so I have this code. Basically it says when you select the object on screen, assign it as your enemy. If you select it again, it deselects it as your enemy. If you select something else, that becomes your enemy instead. It works just fine. The problem I have is if you click on an empty part of the screen, basically selecting nothing, then I get the usual “NullReferenceException: Object reference not set to an instance of an object”… which is correct based on this code.

The issue is that I need it to be ok to click on nothing. So how do I get rid of the error, when you click, but hit nothing?

void Update () 
	{
		if(Input.GetMouseButtonDown(0))
		{
			RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
			
			
			if(hit.collider != null  hidingSpot == null  hit.collider.tag == "Enemy")
			{
				enemy = hit.collider.gameObject;
			}
			else if(hit.collider.gameObject == enemy)
			{
				enemy = null;
			}
			else if(hit.collider.tag == "Enemy"  enemy != null)
			{
				enemy = hit.collider.gameObject;
			}

		}
	}

If you take a look at the scripting reference entry for Physics2D.Raycast they wrap all of it up in

if (hit != null) {
    // Code goes here
}

In your code, if hit is null it will skip the first if then go on to the else if cases, checking against the hit object which is not there (which is why you get the exception)

They check if hit.collider is null, actually. hit is not going to be null, ever.

void Update () 
	{
		if(Input.GetMouseButtonDown(0))
		{
			RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
			
			
			if(hit.collider != null) 
			{
				if(hidingSpot == null  hit.collider.tag == "Enemy")
				{
					enemy = hit.collider.gameObject;
				}
				else if(hit.collider.gameObject == enemy)
				{
					enemy = null;
				}
				else if(hit.collider.tag == "Enemy"  enemy != null)
				{
					enemy = hit.collider.gameObject;
				}
			}
		}
	}

Thanks guys. That took care of it. I appreciate the help!