1
votes

I have problem with triggers in my 2D game in Unity. I want to make enemy die when he triggers with player's weapon. The problem is there are two colliders attached to enemy (tagged "Enemy"):

  • one is box2d collider which is used as normal collider
  • second is sphere collider which is set as trigger and is used in script to check whether there is a player in range

I got sword object, which has sprite renderer, box collider (set as trigger) and script:

void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Enemy")
        {
            if(!other.isTrigger)
            {
                Debug.Log ("enemy");
                Destroy (other.gameObject);
            }
        }
    }

Screenshot of scene: http://i.stack.imgur.com/eVtRX.jpg

Screenshot of Enemy gameObject: http://i.stack.imgur.com/9R5a6.jpg

So in general it sometimes works, but sometimes doesn't. When I disable sphere collider at enemy, everything works great, but I need to have it to check if there is player in range. How can I fix it?

1
Are you moving the weapon with transform? Transform moves the GameObject immediately and doesn't affect collisions.Elias Kosunen
I move it using animation (I rotate player's hand). I think it has nothing to do with moving, but with two colliders attached to enemy.Przemotar

1 Answers

3
votes

you should Make sure two things in OnEnterCollider2D

1) Make sure both the gameobjects participating in OnEnterCollider2D must not be destroyed. If one has to be destroyed then it should be destroyed with some time later.

2) Make sure one of the game object participating in collisions has to have rigidbody attached with isKinematic unchecked.