Search Unity

OnCollisionEnter2D Problem in .exe file

Discussion in '2D' started by CordiTeo, Aug 11, 2019.

  1. CordiTeo

    CordiTeo

    Joined:
    Dec 21, 2018
    Posts:
    2
    Hello evryone, i'm tryng to develop a simple gamescene, there is a square (that is the player) and a platform under him. I just want to make the square able to jump only when he is touching the ground. So i wrote these code:

    Code (CSharp):
    1. public bool isGround = false;
    2.     public Rigidbody2D rb;
    3.     public float jumpForce = 450f;
    4.     public Text status;
    5.     void Start()
    6.     {
    7.    
    8.     }
    9.  
    10.     void Update()
    11.     {
    12.         if (Input.GetKeyDown(KeyCode.W) && isGround)
    13.         {
    14.            rb.AddForce(Vector2.up * Time.deltaTime * jumpForce, ForceMode2D.Impulse);
    15.         }
    16.     }
    17.  
    18.  
    19.     private void OnCollisionEnter2D(Collision2D collision)
    20.     {
    21.         if (collision.gameObject.tag == "Ground")
    22.         {
    23.             status.text = "Ground";
    24.             isGround = true;
    25.         }
    26.     }
    27.  
    28.     private void OnCollisionExit2D(Collision2D collision)
    29.     {
    30.         if (collision.gameObject.tag == "Ground")
    31.         {
    32.             status.text = "NotGround";
    33.             isGround = false;
    34.         }
    35.     }


    It works properly in Unity but when i try to buildAndRun the scene the square doesn't jump anymore...

    Do you have some idea?
     
    Last edited: Aug 11, 2019
  2. masterlewis05

    masterlewis05

    Joined:
    Jan 16, 2016
    Posts:
    8
    Assuming you set the values / rb manually in the inspector, you could try setting them in the start function to see if any have reset: (Don't know if this happens)
    Code (CSharp):
    1. void Start()
    2. {
    3.     rb = gameObject.GetComponent<Rigidbody>();
    4.     jumpForce = 450f;
    5.     isGrounded = false;
    6. }
    You may also want to check if your Player is not on the floor at the start of the game. If so, the OnCollisionEnter2D function may not run, as they never "Entered" the floor collider. If you want the Player on the floor at the start, you can change OnCollisionEnter2D to OnCollisionStay2D .

    Haven't tried any of this out but this would be my go to.