Raycasting bug when checking if player is grounded

Greetings. I have the following problem. I am casting a ray to check if the player is grounded and it works properly. When I press space I jump and set isJumping flag to true and when I land to false. The problem is that sometimes when I jump the isJumping flag is set to false because the raycast still gives that the player is grounded. It is some kind of a race condition maybe since it happens 1 out of 10 times but is really annoying. My ray has a fixed length and I have set the layermask as well.

My recommendation is to move the raycast into its own function that returns a bool. Call this everytime you need to.

public bool IsGrounded(){
//layermask stuff
return Physics.Raycast(......);

This way, you can add the if(IsGrounded()) before you set your isJumping to true. Next, OnCollisionEnter, add something like:

isJumping = false;

To ensure that your raycast is reset consistently when grounded.

My long term recommendation is to actually get rid of the isJumping variable entirely if you can, unless you need it for something else.

But how can I set the landing animation if I do not check whether the player is grounded every few frames? In my game the player can run on walls and make huge jumps. I need to detect whether a player is jumping or has simply fallen of a wall. Maybe i should try to use like you suggested to surround each walkable object with a trigger and to check if the player is grounded only after they leave the trigger zone.