Object click with RaycastHit? [BEGINNER]

The code below isn’t working. It’s printing “preraycast” and “predef” but not “pretagcheck” or “tag”. What am I doing wrong? P.S. I did check the name and tag of the gameObject. By the way, how do I properly insert code? Thanks! (This is a 2D game)

//code

private void Update() {
        

    if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("preraycast");
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            Debug.Log("predef");
            if (Physics.Raycast(ray, out hitInfo))
            {
                Debug.Log("pretagcheck");
                if (hitInfo.collider.gameObject.tag == "Wheat")
                {
                    Debug.Log("tag");     
                }
            }
        }
        
        
    }

Hello, the problem is that Physics.Raycast only works on 3D colliders. If you place a cube with a box collider and the matching tag in your scene, then you get to the last log.

With 2D Colliders you have to use the Physics2D functions. However, since this would only be limited to the x/y plane, Unity gave us the Physics2D.GetRayIntersection function, with which you can check whether a 3D raycast intersects with a 2D collider.

In your case your code should look like this:

if (Input.GetMouseButtonDown(0))
{
    Debug.Log("preraycast");
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    Debug.Log("predef");
    RaycastHit2D hitInfo = Physics2D.GetRayIntersection(ray);

    if (hitInfo.collider != null)
    {
        Debug.Log("pretagcheck");
        if (hitInfo.collider.gameObject.tag == "Wheat")
        {
            Debug.Log("tag");
        }
    }
}

Thank you so much! I didn’t realize there was a separate one for 2D and 3D.