Object reference not set to an instance of an object (Raycast)

I have just finished a game for windows phone, and i have had this error all thorough the process and it has never stopped me doing anything. However when I export to visual studio it will not run because of this error.

Error : NullReferenceException: Object reference not set to an instance of an object
GameManager.Update () (at Assets/Scripts/GameManager.cs:90)

void Update () {
	
	RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

	if(Input.GetMouseButtonDown(0)){
			mouseClicked = true;	
   		    				
		//Clicked Good Box 1
			if(hit.collider.tag == "GoodBoxTag1"){
			Debug.Log ("GB1 Hit");
			
			//Timer Starts
			//GB1Hit = true;	
			GB1Clicked = true;
		}
      }
  }

The error occurs with (hit.collider.tag == “GoodBoxTag1”) I have seen other similar problems and the fixes but they all do a different method of ray casting.
Any help with this would be greatly apprenticed.
(P.S. This is my first post so sorry for any incorrect formatting)

1 Answer

1

if(hit != null && hit.collider != null && hit.collider.tag == “GoodBoxTag1”)

Thank you that solved it :D