Detect an area for objects, as fast as possible, 2D game

I have my main character, who can suddenly transform into a Dinosaur, destroying all objects it collides with, except the ground.

The dino has two boxcolliders, one that fits its shape, and one that I call the detector, which is slightly bigger than the first. I have this detector, in order to trigger with the objects before the real collider, and destroy the objects without causing any physics to push the player object in a direction when it collides.

The problem is when I transform from small guy, into dino. It happens like this:

  1. Transform into dino, begin!
  2. Position detectionCollider
  3. detectionCollider.enable = true; (Detection collider is disabled when not in dino shape)
  4. Expand playerCollider

But, for some reason step 4 happens before the detector has collided with objects and destroyed them. If you’re wondering, I am not actually destroying them, but just disabling their renderers and colliders.

To solve this problem I made a coroutine, that waits 0.02f seconds between step 3 & 4. This works to some point, but sometimes 0.02f is simply not long enough. I am also afraid if this will act differently depending on what machine that is running the game? (I’d like an answer to this “subquestion” as well).

I am not satisfied with this solution. So basically how can I detect an area for objects, “destroy” those, wait for confirmation AND THEN expand playerCollider.

I guess I could have the detectorCollider enabled at all time, and use a bool to decide if Dino is active and objects should be destroyed. But I feel like it would cost more performance for my game, or is it such a minimal cost, that I shouldn’t care?

The problem that you’re most likely running into is that the physics system hasn’t finished a frame between when you enable the detector and when you expand the player’s collider.

You’re on the right track with your coroutine solution - instead of yield return new WaitForSeconds(0.02f) you would instead do something like yield return new WaitForFixedUpdate(). This should guarantee that a fixed update frame is finished before the coroutine continues, thus allowing OnTriggerEnter events to propagate to your detector. You might need two WaitForFixedUpdates in a row.

Otherwise, the performance impact from leaving the detector enabled all the time is probably inconsequential, so you could do that instead.