Raycast through enemies, stop at wall

My game’s playable character has an attack that can go through enemies but not parts of the environment (i.e., walls, terrain); essentially, to use an example from an already existing game, think of sniper bullets from any modern FPS. So, in a situation with two enemies and no wall and in a different situation with two enemies and a wall in between the two, these are the outcomes that should occur.

alt text

The problem I’m having is getting it (the attack) to go through the first enemy but stop when it connects with something that’s not an enemy, in this case part of the game environment.

So far, seeing as the regular Raycast function only works for the first object it hits, I tried using RaycastAll without success, and that didn’t work nearly as well as I hoped, even when I set everything in the environment to Ignore Raycast. So to sumarize, I need help creating an attack that does the following two things:

  1. Continues through an enemy to hit whatever is behind it, and to continue moving as such if there is another enemy behind the first enemy to get hit.
  2. Stop immediately when it hits part of the environment, such as a wall, desk, or piece of terrain.

RaycastAll is your best bet. The only thing that’s tricky about it is that the order is not guaranteed so you will need to sort by distance before iterating through the list. This can be done quickly and easily using Linq.

RaycastHit[] hits;
hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F); // or whatever...

foreach(RaycastHit hit in hits.OrderBy(x => x.distance))
{
    //check if it's an enemy or a wall.

    //do damage if it's an enemy, break if it's a wall;

}

Of course this will also require

using System.Linq;