OnCollisionEnter2D and OnCollisionExit2D not working properly

On the game, when you click the up arrow, the gravity is inverted. So when you click the down arrow, the gravity is set back to normal.

I don’t want the player to be able to flip up and down unless it is touching the ground. Below is what I have for the player movement. Currently, none of the debug logs are showing, and when I click the up arrow isTouching = true, when it should equal false.

I do have my ground objects tagged as Ground.

{

public float speed;
public Rigidbody2D rb;
public bool isTouching;

void Start()
{
    Rigidbody2D rb = GetComponent<Rigidbody2D>();
    isTouching = true;
}

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    Vector2 movement = new Vector2(moveHorizontal, 0.0f);
    rb.velocity = movement * speed;

    if (Input.GetKeyDown(KeyCode.UpArrow) && (isTouching = true) ){
        rb.gravityScale = -25;
    }

    if (Input.GetKeyDown(KeyCode.DownArrow) && (isTouching = true))
    {
        rb.gravityScale = 25;
    }
}

void OnCollisionEnter2D(Collider2D collider)
{
    Debug.Log("entered");
    if (collider.gameObject.tag == "Ground")
        isTouching = true;
}

void OnCollisionExit2D(Collider2D collider) {
    Debug.Log("exited");
    if (collider.gameObject.tag == "Ground")
        isTouching = false;
}

}

@sylviafinger

OnCollisionEnter2D () and OnCollisionExit2D () both require a datatype of Collision2D to be passed in, not Collider2D

Change your methods to the following:

void OnCollisionEnter2D(Collision2D collider)
 {
     Debug.Log("entered");
     if (collider.gameObject.tag == "Ground")
         isTouching = true;
 }
 void OnCollisionExit2D(Collision2D collider) {
     Debug.Log("exited");
     if (collider.gameObject.tag == "Ground")
         isTouching = false;
 }

Next time, try to consult the Unity API when you’re having problems with collisions as it’s normally the first place many people have errors.

OnCollisionEnter2D - Unity Scripting API

Hope it helps.