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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Why OnCollisionEnter no working???

Discussion in 'Physics' started by unity_tlv1IB9XIAbbtw, Sep 16, 2021.

  1. unity_tlv1IB9XIAbbtw

    unity_tlv1IB9XIAbbtw

    Joined:
    Sep 30, 2020
    Posts:
    25
    I just use this: GameObject iceCube = GameObject.CreatePrimitive(PrimitiveType.Cube); to create an ice cube and when I use the AddComponent to add a script like this:
    void OnCollisionEnter(Collision collision)
    {
    if (collision.collider.name == "player")
    {
    player_health -= 10;
    }
    }
    It doesn't work at all. Somehow I cannot even detect the collision and I even print something when colliding but still no result. Any suggestion?
     
  2. UncleanWizard

    UncleanWizard

    Joined:
    Jun 5, 2021
    Posts:
    38
    Did you add a collider as well?
    Code (CSharp):
    1. cube.AddComponent<BoxCollider>();
    This is why you should be using a prefab and use GameObject.Instantiate so Unity will handle all the components and children creation for you.
     
  3. unity_tlv1IB9XIAbbtw

    unity_tlv1IB9XIAbbtw

    Joined:
    Sep 30, 2020
    Posts:
    25
    Thank you for your help!