It is bad for performance to enable and disable a collider on each update

Hi,
since at each update I have to temporarily exclude a collider to do some collision tests. I would like to know if enabling it and then disabling it at each update can cause performance problems.
My code looks something like this:

void Update()
{
    collider.enabled = false;

    // Collision tests...

    collider.enabled = true;
}

it wont kill any game, but can always check with Profiler to see how much it costs…
(i dont know if physx need to regenerate some world collision data at that point then)

Could be better to use physics layers, or raycast layers (if using raycast),
or ignorecollision Unity - Scripting API: Physics.IgnoreCollision
or other options, depending what your test is.

2 Likes

According to the profiler there don’t seem to be any problems, but I still have some doubts.

Generally speaking static colliders (especially complex ones, such as meshes) are optimized to… well, to be static. Data structures used for static objects are usually expensive to build, but allow for very fast calculations once the tree is fully constructed. Changing a static scene will invalidate the tree and trigger a rebuild - a situation you should try to avoid.

Dynamic objects (objects with rigidbody) on the other hand usually handle disabling relatively well. They are the opposite: slower to process, but relatively fast when it comes to handling changes to collider position (or existence).

Using collision layers (as long as layers do not change dynamically), is by far the fastest option.

Then again for smaller scenes you will probably be fine either way.

1 Like

In the end I decided to do some tests and it turned out that temporarily disabling the collider before each cast has a not negligible impact on performance. It does not seem to depend on the number of non-static colliders but on the overall number of colliders in the scene. By increasing the number of colliders, the relative impact on performance decreases, probably because it is dominated by the actual calculation of the cast.
I also found that it is much more efficient to set collider.isTrigger to true and then false, before and after each cast. Alternatively, it is just as efficient to use the NonAlloc version of the cast and then filter the resulting hits.

4 Likes