How to stop raycast at first object hit?

Hey everyone! I have made a script that interacts with the object raycast hit. However in some cases the ray passes through the object, hits the plane then returns the plane collider, not the actual object’s collider. I want it to somehow stop at the first collider hit, so I can use its value with hit.collider. Thanks in advance.

if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit))
            //if its close, write its name and interact
            if (hit.distance < 2.5 && hit.collider.tag != "Untagged")

                    interactionText.text = "(E) " + hit.collider.tag;

                if (Input.GetKeyDown("e") )

In case anyone still need an answerer to this I suggest Stopping a raycast after hit - Questions & Answers - Unity Discussions

For anyone looking at this question, I’d suggest using layer masks and utilizing layering for a more “proper” method of specific object raycast hit determination, rather than relying on object tags.

First make sure the objects in question are on layers dedicated to their type (however works best for your needs). Then use LayerMask.GetMask(“LayerName”) to find the mask required for raycast limiting (note than LayerMask.NameToLayer() will return the specific layer number, not the mask required for a raycast!). I tend to generate the masks I’ll need in Awake().

As well, the use of Infinity isn’t a good choice for performance. Likely your situation will have a known distance limitation that can be applied (such as at most the camera’s far clipping plane distance). My opinion is that since raycasting can be quite an expensive call to make, limiting its scope by layer masks and known distances can help.