Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved OnCollisionEnter not working when checking for layer

Discussion in 'Scripting' started by BlitzKeeg, Jun 8, 2023.

  1. BlitzKeeg

    BlitzKeeg

    Joined:
    Jun 8, 2023
    Posts:
    2
    Hello, so I have a Capsule rigidbody with collider working as the PC and im trying to detect collisions with walls and other things on a specific layer. I checked that the test wall has a collider (box collider) set to the right layer (water for now, no reason) and that neither of them are set to isKinematic or isTrigger in the editor. When i was debugging, OnCollisionEnter would send a debug message when I hit the wall, and i even checked the layer mask this way and it returned the correct layer. But when i did this:
    Code (CSharp):
    1. OnCollisionEnter(Collision collision)
    2. {
    3.         if(collision.gameObject.layer == mask )
    4.         {
    5.             Debug.Log(collision.gameObject.layer);
    6.          }
    7. }
    I no longer get the debug message. Idk why and ive tried just about every other fix i could find so some extra opinions would be much appreciated, thanks. *also i checked the mask variable on my player controller and its set to the right mask **also,also, the function im trying to put in place of the debug message puts the player into isKinematic to move it to a ledge location but the wall stays normal
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,468
    A single integer layer number is not a multi-layer bit-mask where each bit represents a layer.

    Do need to shift a bit something like this:
    Code (CSharp):
    1. void OnCollisionEnter(Collision collision)
    2. {
    3.     var hitLayerMask = 1 << collision.gameObject.layer;
    4.     if (hitLayerMask & mask)
    5.     {
    6.         Debug.Log(collision.gameObject.layer);
    7.     }
    8. }
     
    BlitzKeeg likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
  4. BlitzKeeg

    BlitzKeeg

    Joined:
    Jun 8, 2023
    Posts:
    2
    that was very helpful, i had not found this channel before and i understand whats up now, thank you
     
    MelvMay likes this.