Performance: RaycastAll() vs a few Raycast() with layer masks

What would be faster, RaycastAll() and then determining which objects were hit, or a few Raycast() with layer mask for each object?

I’m detecting what’s under cursor, if an enemy → change cursor to attack, if building → change cursor to house, etc. if two objects were hit by raycast (enemy and building) I still need to detect both as e.g. worker unit won’t attack even if enemy is under cursor

The only answer I found was about single execution of Raycast

For starters, this has to create a C# array which will then get thrown at the GC so you’ll pay for that collection. You should avoid those types of calls. In 3D you’ll have to use the “NonAlloc” variant of that call which populates an existing array which you can reuse. Likely this will give you better performance (over multiple Raycast calls) because it’s a single round-trip to the engine and back to the scripts and produces no GC waste.

In the end though, these kinds of questions are not easy to answer and is why there’s a built-in profiler. Set-up a simple test for your usage and see what gives you best results.

1 Like