- Home /
OnTriggerEnter2D working sporadically
I'm making a shooter. I have a player ship firing bullets at enemies and destroying them when their health reaches 0. Most of the time this works great. The enemies and the bullets are pooled.
Sometimes an enemy will spawn and when bullets are fired at it OnTriggerEnter2D is never called. Their components appear to be set up the right way, IsTrigger is set to true, etc.
The OnTriggerEnter2D calls for every other object work fine. I'm not sure where to go from here.
//enemy trigger code
void OnTriggerEnter2D( Collider2D collider)
{
if (collider !=null && collider.gameObject != null && collider.gameObject.tag.Equals("PlayerBullet"))
{
hitSignal.Dispatch();
if (health <= 0)
{
destroyedSignal.Dispatch();
}
}
}
If the same enemy is always running into the same problem, is this script attached to that enemy and is the enemy wide enough that the bullet cannot go completely over the object in one frame.
It can be difficult to debug "sometimes", since that means sometimes it works, too. You might be able to distinguish when it works from when it doesn't. To do this, play until you encounter one of these "ghost" enemies, pause the game, and take a good, hard look at its settings in the Inspector, and what might be different from others of its kind.
Answer by fendorio · Apr 08, 2014 at 06:47 PM
Unsure if this will be it.. But have you tried switching the setting in the RigidBody2D component 'Collision Detection' from discrete to continuous?
Sometimes a object travelling at a high speed (possible speed is a trigger in causing this?) it will collide 'too fast' and not be registered that frame.
Script ref: Rigidbody.collisionDetectionMode
Setting the collision mode to continuous does come with a performance overhead mind.
My knowledge on this isn't all that great, however I did run into a similar problem with collision detection a few days back and this was the fix to my problem.
I was thinking about that too so I set the bullets and enemies rigidbody2d to continuous but I'm still getting the same bug.
Answer by AYatsko · Jun 30, 2015 at 11:07 AM
I was having the same problem when a character was falling through a collider, not a trigger though. I increased the linear drag of the character just a little and it solved the problem.