Search code examples
c#unity-game-engineif-statementcollision-detection

Unity2D collision, if statement


I have this bit of unityCode to check if a character is grounded

private void FixedUpdate(){
    is_on_ground = false;

    // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
    // This can be done using layers instead but Sample Assets will not overwrite your project settings.
    Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
    for (int i = 0; i < colliders.Length; i++) {
        if (colliders[i].gameObject != gameObject) {
            is_on_ground = true;
        }
    }
}

Can someone explain what the if-statement if (colliders[i].gameObject != gameObject) does?


Solution

  • It is checking to assure the current collider found in the Overlap is not the gameObject that the script is on.

    It is rather odd to have as it is a ground test to a specific layer so your object that is grounded should most likely not be part of the ground.