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