- Home /
Best way to limit RaycastAll stopping at a certain object
Imagine a Bomberman like explosion that hits everything in a line until a wall is hit. Or a laser weapon, hitting through enemies or certain objects, until a wall is hit.
What would be the most effective way to get the objects that are hit?
I came up with:
Using RaycastAll(), then sort by distance ascending, then loop through all hits and stop if a wall is found.
Using an initial Raycast() with a Layermask to get the distance to the nearest wall, then using RaycastAll() with that distance as maximum.
Using repeated Raycast(), after each iteration setting origin to the position of the last hit object, until a wall is hit.
Hello, have you ever figured out the answer to your problem? I see that this was dated back at April 2014, and I got a similar question like this.
Option 1 is what I have been using and I think it's the most versatile.
Yes, I also went with RayCastAll, except I didn't apply a full sorting, just looped twice through the hits - in first loop, remember the closest wall object, in second loop get all hit objects that are nearer. Slightly faster if you hit a lot of objects.
^ The first wall object hit in the RayCastAll array isn't necessarily the first wall distance-wise, though. The API for RaycastAll specifically sates that that hits are not neccessarily sorted by distance.
That's why OP added 'then sort by distance ascending'.
Option 1 is inefficient, Option 3 is complicated, and Option 2 looks like the best.
Answer by hu90 · May 20, 2015 at 11:17 AM
My opinion on your solutions :
Inefficient. Depending on the case, RaycastAll can come across a large number of objects, even when a wall is very close. Add to that the time needed to sort by distance, and you can see how this is quite inefficient. It won't be that bad if the raycast distance is low though.
Efficient and simple. If you can set up a LayerMask for the walls, I'd recommend this solution. The initial Raycast is worth its cost, as the subsequent RaycastAll will be optimal.
More complicated, but you'll get the objects sorted by distance. Not sure this is better than option 2 with sorting by distance though. You may have to make sure you do not hit the same object twice.
TL;DR: Use Option 2.
Your answer
![](https://koobas.hobune.stream/wayback/20220613143821im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Third Person Shooting Script Stopped Working 1 Answer
FPS shooting 1 Answer
Tower of Hanoi style 1 Answer
problem with scripting 1 Answer
Random Raycast inside crosshairs 1 Answer