Search code examples
functionunity-game-engineunityscript

Unity JavaScript OnCollisionEnter with 2D gameObject


Im trying to destroy a gameObject (in my case a 2d ball) when my player comes into contact with it with the built-in OnCollisionEnter function. My script is only attached to the player. Both the player, and the ball(battery) have 2d box colliders, and rigidbodies. Perhaps the fact that they are 2d colliders instead of regular has something to do with the problem? Ah! yes I almost forgot to mention the problem; it's not working. Its niether destroying, or printing "hit".... and oh yes, i DID name the ball "battery". thAnks so much I would very much appreciate some help!

UnityScript Code:

function OnCollisionEnter(batt : Collision)
{
    if(batt.collider.name == "battery")
    {
        Destroy(batt.gameObject);
        Debug.Log("Hit");
    }

}

Solution

  • if you are using unity's 2d toolset, instead of OnCollisionEnter you use OnCollisionEnter2D, and inside the variables, instead of batt: Collision, you need to change it to batt: Collision2D, hope this helps :), also, you said your both objects have 2d box colliders and rigidbodies, make sure it's a 2d rigidbody and not a 3d rigidbody (default)