OnCollision doesn't work

Hi Guys. I’m trying to make a playerObject jump only when it’s touching the ground. So I need to use a OnCollision to check if it is grounded. The think is that OnCollison simply doesn’t work. Player has a rigidbody and collider, floor has a rigidbody and collider aswell.
Here is the code:

    // Use this for initialization
    void Start() {
        _charController = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
        

    }

    void OnCollisionEnter(Collision col)
    {
       if (col.gameObject.name == "floor")
            Debug.Log("Hit the floor");
            isGrounded = true;
    }

    void OnCollisionExit(Collision col)
    {
        if (col.gameObject.name == "floor")
            Debug.Log("Hit the floor");
        isGrounded = false;
    }



    // Update is called once per frame
    void Update() {


        MovementFunction();


        if (isGrounded == true)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                _charController.Move(jumping);
                isGrounded = false;
            }
        }


    }

Hi there!

Huh, that’s interesting. I made a small test doing similar to what you have and I got it to work without problems. A few things to note:


  1. MAKE SURE that the ground object is named “floor” (lowercase f too) since that’s what you’re expecting in your OnCollisionEnter and OnCollisionExit functions.

  2. Maybe you want curly braces around your if statements in the two OnCollision functions? I don’t know if you want the isGrounded = ___;to only happen if it collides with "floor", but I would guess you would, so I’d suggest adding the curly braces.


Here is my testing code where I managed to get it to work:

public bool isGrounded = false;

private Rigidbody rb;

void Start() {
    rb = GetComponent<Rigidbody>();
}
 
void OnCollisionEnter(Collision col) {
    if (col.gameObject.name == "floor") { 
        Debug.Log("ON the floor");
        isGrounded = true;
    }
}

void OnCollisionExit(Collision col) {
    if (col.gameObject.name == "floor") { 
        Debug.Log("OFF the floor");
        isGrounded = false;
    }
}

Ground checks, especially when using OnCollision functions, can get a little weird sometimes. For example, what happens if the character is on a slope? What if you are hitting a wall, but not necessarily on the ground? Raycasts are popular (and effective) ways for ground checks and using the OnTrigger functions can sometimes work better too. I’m not saying that the OnCollision functions won’t work though. They could totally work. It’s just that, depending on your project, issues could arise with it.

I already added curly braces and I’ve checked the tag and the name of the floor. I cant use OnTrigger because object will fall under the floor then, but I added a transparent box collider with a floor tag jusy a little bit above a floor and it works now. So I have a temporary solution.