Search Unity

Question Collisions not Working Properly

Discussion in 'Scripting' started by Eisenwelle, Apr 8, 2021.

  1. Eisenwelle

    Eisenwelle

    Joined:
    Mar 18, 2021
    Posts:
    22
    I have my bool isGrounded set to false automatically, and it's set to true when my player is in contact with an object on the Ground layer. Here's my script:
    Code (CSharp):
    1. void OnCollisionEnter(Collision coll)
    2.     {
    3.         isGrounded = false;
    4.         Debug.Log("Airborne");
    5.  
    6.         if (coll.collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
    7.         {
    8.             isGrounded = true;
    9.             Debug.Log("Grounded");
    10.         }
    11.     }
    The problem is, isGrounded is always set to true, and no matter what I change, I can't get it to set to false when I'm no longer touching a ground object. I'm sure there's a simple solution, but my beginner brain has expended it's knowledge, so any help is appreciated!
     
  2. stain2319

    stain2319

    Joined:
    Mar 2, 2020
    Posts:
    417
    I am a bit new myself but I think you will need an OnCollisionExit method that sets it back false when the collision ends
     
  3. Eisenwelle

    Eisenwelle

    Joined:
    Mar 18, 2021
    Posts:
    22
    That worked, and yeah, that was probably the most simple solution there could've been. Many thanks!
     
    Kurt-Dekker likes this.