Why raycast doesn't hit any collider?

I try to make a roulette racetrack for a mobile game.
199520-ractrackscheme.png

There is 37 box(sprite) in the racetrack, each square box have a Box Collider 2D and each rounded box have a Polygon Collider 2D.

my code:

void Update()
    {
        if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.touches[0].position);
            RaycastHit hit;
            Debug.DrawRay(ray.origin, ray.direction*100, Color.yellow, 100f);
            Debug.Log("Touch Something");
            if (Physics.Raycast(ray, out hit))
            {
                Debug.Log("Something Hit");
                Debug.Log(hit.collider);
                if (hit.collider != null)
                {
                    Debug.Log("collider Hit");
                }
            }
        }

    }

I would like to do something when I hit the collider of a box. When I test my code, the only debug.log that work is “Debug.Log(“Touch Something”)”.

result for Debug.DrawRay
199521-raycast.png

We can see that the raycast doesn’t hit any collider but I don’t know what I should change, please help! ^^

I would personally be very selective on using raycasts, since they do use a good bit of performance. Maybe a better way will present itself in the future, or I would look into Physics.OverlapSphere and just use raycast to determine where to spawn it, so it only reads once(or sparingly).

But read up on the documentation :

And also maybe look into layerMasks :
https://forum.unity.com/threads/defining-layers-in-raycast.36349/

Another way to go, would be to just use positions as a reference. But one thing that will greatly help your future coding endeavors is this coding structure I made : Performantly handle Script to Script Communication - Questions & Answers - Unity Discussions , as this will make your code more performance light, and easier to understand :slight_smile:

I replace my 2D colliders by 3D colliders and now everythings is working.