Przemotar
Przemotar

Reputation: 11

Unity OnTriggerEnter2D sometimes doesn't work

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"):

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: https://i.sstatic.net/eVtRX.jpg

Screenshot of Enemy gameObject: https://i.sstatic.net/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?

Upvotes: 1

Views: 4407

Answers (1)

Noor Ali Butt
Noor Ali Butt

Reputation: 817

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.

Upvotes: 3

Related Questions