Some syntax correction on using an array of Rays inside a foreach for doing Raycasts

I know the title isn’t the easiest to understand but that is roughly the gist. You understand how normally when you do the raycast check - if (physics.raycast( - You can use a pre-defined ray instead of typing out the position and direction?

Well I’m trying to do the same thing, but using a foreach loop to fire six different rays at once. At least that’s the plan. Imagine checking on each side of a hexagon to see if there are any neighbours.

public Ray[] rays;  

rays = new Ray[6];

rays[1] = new Ray(gameObject.transform.position, gameObject.transform.forward);
rays[2] = new Ray(gameObject.transform.position, (gameObject.transform.up * 60));

On a second note, I imagine I’ve done that 60 degree check incorrectly, but the point is, I’m trying to use an array of rays to simplify the checks and make a potential foreach out of them for the raycasting. Unfortunately it’s impossible for me to memorise syntax, plus this is new territory for myself. This is what I’ve manged thus far.

foreach (Ray item in rays)
{
   RaycastHit hit;

   if (Physics.Raycast(rays, out hit, 80))
   {
        print(hit.collider.gameObject.name);
        Debug.DrawRay(gameObject.transform.position, gameObject.transform.forward);
   }
}

Simple enough logic. For every ray I’ve defined in that rays array, I want to use their values inside that raycast check. Unfortunately rays is incompatible.

I imagine there’s a correct way to do this, but I don’t know the required syntax. Any insight from a more seasoned coder would be highly appreciated.

All the best.

It looks like you’re iterating over an array, but then passing the entire array to the Raycast function. When using foreach, it will work through the contained code block once each time for each member of the array, giving you access to each individual item with (in this case) the Ray item variable.

foreach (Ray item in rays) { ... if (Physics.Raycast(item, ...)) { ... } }

You can consult the Unity scripting reference if you have further trouble Unity - Scripting API: Physics.Raycast