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") )
{
//print(hit.collider.tag);
hit.collider.gameObject.GetComponent<Interact>().Interaction(hit.collider.tag);
}
}
The issue probably is with the object collider you want returned. Cause Physics.Raycast() will give the the hit of the first collider it finds, afaik. With RaycastAll(), you could check (just for debugging) how many colliders are hit.
Answer by Giantbean · Jul 17, 2019 at 10:22 PM
In case anyone still need an answerer to this I suggest https://answers.unity.com/questions/384355/stopping-a-raycast-after-hit.html
Answer by AnOrdinarySandwich · Jan 31, 2021 at 12:15 PM
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.