How do I fix 2d Grid Instantiating?

I am trying to make a 2d grid where if you click on a grid square it instantiates a turret prefab to the mouse x position.
The script detects that you are clicking but not that you clicked on a gameObject.

Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurretSpawner : MonoBehaviour
{
    [SerializeField] private GameObject turret;
    [SerializeField] private GameObject turret1;
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector2 mousePos2D = new Vector2(cursorPos.x, cursorPos.y);

            RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
            if (hit.transform != null)
            {
                Debug.Log(hit.transform.gameObject.name);
                Debug.Log(hit.transform.gameObject.name);
                if(hit.transform.gameObject.tag == "GridObject")
                {
                    if (cursorPos.x >= 0)
                    {
                        Instantiate(turret, new Vector3(cursorPos.x, 5 + 11, 0), Quaternion.identity);
                    }
                    else
                    {
                        Instantiate(turret1, new Vector3(cursorPos.x, 5 + 11, 0), Quaternion.identity);
                    }
                }
            }
        }
    }
}

I had to give it a BoxCollider2D. I set it to IsTrigger so it had no collisions and it worked. :smiley: