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:

  1. Using RaycastAll(), then sort by distance ascending, then loop through all hits and stop if a wall is found.
  2. Using an initial Raycast() with a Layermask to get the distance to the nearest wall, then using RaycastAll() with that distance as maximum.
  3. Using repeated Raycast(), after each iteration setting origin to the position of the last hit object, until a wall is hit.

My opinion on your solutions :

  1. 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.
  2. 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.
  3. 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.