Comparing RayCastHit GameObject to Array of GameObjects

What I am trying to do is. When the raycast hits an object, take that objects and see if that game object is also in the array of game objects that was created. I have defined all items in the game object array. Here is a snippet of code. I cannot quite figure out why it works but at the same time also throws a reference exception.

public class GameManager : MonoBehaviour 
{
	public GameObject[] tiles;
private string temp;
private string nameToCheck;

void Awake()
{
	SetupGame();
}

void Start () 
{

}

void Update () 
{
	CheckRayCast();
	CheckRayCastTouch();
}
void CheckRayCast()
{
	if(Input.GetMouseButtonDown(0))
	{
		Vector3 mousePos = Input.mousePosition;
		Vector3 screenPos = Camera.main.ScreenToWorldPoint(mousePos);
		RaycastHit2D hit = Physics2D.Raycast(screenPos, Vector2.zero);

		if(hit)
		{
			temp = hit.collider.name;
			nameToCheck = temp;

			foreach(GameObject x in tiles)
			{
				if(nameToCheck == x.name)
				{
					Debug.Log(hit.collider.gameObject.name);
				}
			}
		}

Here it will give me the name of the object hit in debug but it also throws a reference exception. Not sure whats going on here.

“RaycastHit2D” is s struct. So your if check is pointless:

if(hit)

This will always be true. A struct can’t be null. You should check if hit.collider is set.

Next thing is, why do you compare the names of the gameobjects? Comparing strings is slow and if two objects have the same name the result can be wrong. Just compare the references:

     if(hit.collider != null)
     {
         GameObject obj = hit.collider.gameObject;
         foreach(GameObject x in tiles)
         {
             if(obj == x)
             {
                 Debug.Log(x.name);
             }
         }
     }

edit i just saw your comment above. If the “tiles” array isn’t an array of objects in the scene, then of course comparing the references would be nonsense. You haven’t said that in your question.

If the error is indeed in the line if(nameToCheck == x.name) that would mean your tiles array has an “empty slot”. So one of the elements is null.