Search code examples
unity-game-enginecollision-detectionunityscriptgameobject

OnCollisionEnter not working


I have a problem with my onCollisionEnter function in Unity3d. The thing is i have a 3rd person controller who if collides with a boudary object should activate another gameobject and a label.

this is how i have given my code

function OnCollisionEnter(collision : Collision)
{
   if(collision.gameobject1.tag=="tag1")
   {
     // activate game object and label
   }
   if(collision.gameobject2.tag=="tag2")
   {
      // deactivate game object and label
   }
}

the problem is it is entering both the loops and i dunno whether what i have given is wrong or the way i have given. Where am i going wrong?


Solution

  • If the OnCollisionEnter event is firing (you could add a print to make sure), then there are two things to check: tags and colliders

    Tags

    Try

    collision.transform.tag
    

    Also verify that you have selected the right tag for the gameobject.

    Colliders

    In Unity3D the collision callbacks (onCollisionEnter, etc) only happen under certain circumstances. EX: A gameobject (gameobject1) with a collider and rigidbody component will collide with a static (not moving) gameobject (gameobject2) that just has a collider.

    I would look at Box Collider Reference because at the bottom is a Collision action matrix that explains under what conditions collisions occur.