- Home /
OnTriggerEnter2D Not Working
I have a shot prefab with rigidbody 2d and box collider 2d components that is set to be a trigger. However, OnTriggerEnter2D is not set off when it collides with either the player, which also has a rigidbody 2d and box collider 2d, or with an enemy, which has a box collider 2d. None of the objects are kinematic, and they are all on the same layer. Here is the code for collision detection:
void OnTriggerEnter2D(Collider2D collider)
{
Debug.Log ("Entered");
ShotScript shot = collider.gameObject.GetComponent<ShotScript>();
if (shot != null) {
if (shot.enemyShot != isEnemy) {
hp -= shot.damage;
Destroy (shot.gameObject);
}
if (hp <= 0) {
Destroy (gameObject);
}
}
}
Here is the shot prefab:
Here is the enemy prefab (the health script component is the code above):
You mention that a trigger doesn't happen when your shot hits a player, but that script is only attached to your enemy? We haven't seen the setup or script attached to your player or shot so can't diagnose those.
As for your enemy, you need to mark its collider as IsTrigger if you want to use its collider as a trigger.
Answer by AmirBraham · Oct 18, 2016 at 09:10 PM
Hi , OnTriggerEnter2D Not Working because your enemyPrfab needs a RigidBody2D It can be confusing but I believe that this can help you understand more about colliders/triggers : https://docs.unity3d.com/Manual/CollidersOverview.html
I tried adding a rigid body to the enemy, but the collision still isn't happening just like it isn't happening when a shot hits the player.