In C#, is it possible to perform multiple Raycasts in a single function?

G’day everyone,
Long time reader, first time poster.

I’ve never really come across a problem I couldn’t figure out eventually, however this time around I can’t seem to figure it out.

I’ve looked at multiple threads about using multiple Raycasts, and each of them say to use the “else if” function, however that doesn’t help me in this situation. I’ll explain:

We’re creating a simple, 3D bejeweled style game. The code is cheap and nasty, as it was more about doing it in a time limit rather then writing the worlds greatest code.
When the blocks are dropped into the grid, we needed to check the blocks, to see if the colours matched up, and if more then three did, they would then explode.

To do the detection code, I created a simple recursive function that performs four raycasts in each 2D direction of the passed in block. The raycasts had a short length designed to only grab the block next to it, if it found that the block was the same colour, it would call the same function onto that block, continuing until it found the entire ‘chain’ of that colour, adding them all into a list, then finally at the end, deleting them all from said list.

What we found, was that only one of the raycasts would work, the first, Up. Deleting vertical rows of colours was fine. However as soon as it checked the other three directions, the “Physics.Raycast()” would just never return true.

Commenting out the Up section, would then allow for Right to work perfectly fine, however leaving the following ones still not working.

It should be noted that we’ve already changed from a raycast system, and we understand there are much better ways to implement the system, however we’re still curious to know what was happening before.

Can Unity only perform a single raycast per frame, or am I just missing something?

Thanks guys.

I just had this same problem as OP (using a good ol’ for-loop, not recursive). It’s definitely inconsistent behavior on the part of Physics class. After much head bashing I was able to work around using Physics.linecast (with otherwise identical code) and it worked like a charm!

I imagine OP has probably (hopefully) moved on, but maybe this will save someone else wasting an afternoon debugging:)

I bet this function helps you further: Unity - Scripting API: Physics.RaycastAll It casts a ray to all other objects and you can then analyse the current situation by going through all hits one by one in a loop.

Still interesting, would like to know if there is a once per frame maximum per script/object per frame. Please report back.

Raycasts are substantially more expensive than just maintaining the contents of your grid in an array and checking neighbors there.