OnCollisionStay2D not being run each frame

Hello, currently I’m having issues getting OnCollisionStay2D to run each frame. My character isn’t moving and it is constant collision with the ground, and yet, every few frames or so, the collision check just doesn’t seem to run. It is kind of important because I need to check if I’m on the ground before I jump, but occasionally the jump will fail because the collision check doesn’t get run and the groundcheck boolean remains set to false. Anyone know how to fix this?

Here’s the code and the output I got for testing this-

 bool ran = false;
 
void LateUpdate()
    {
        if (ran)
            Debug.Log("Wall checks were run");
        else
            Debug.Log("Wall checks not run");
        ran = false;
    }

void OnCollisionStay2D(Collision2D coll)
    {
        ran = true;
    }

Correct, OnCollisionStay2D runs every physics frame. It’s not meant to run every frame, same as FixedUpdate. You should not run physics code in Update or LateUpdate.

–Eric

1 Like

Ah okay, didn’t know Unity divided itself up like that. Although I just found another reply of yours that says “the FixedUpdate function runs once every physics frame”, and changing the reset variable to run in FixedUpdate instead of LateUpdate makes the check more consistent, but I’m still getting “Wall checks were not run” in my debug, although far less frequently then before. Is there any other reason as to why this still isn’t syncing up properly?

I’m not sure that OnCollisionStay and FixedUpdate always execute in the same order. Since OnCollisionStay can be a coroutine, try using WaitForFixedUpdate in it to make execution order 100% explicit.

–Eric