# OnTriggerEnter doesn't detect collision until at least one of the two colliders move

I'm having trouble coding a melee attack script.

I've set up an attack hitbox that toggles enabled/disabled whenever you press a button (The hitbox itself doesn't move, it just blinks in and out) and I'm trying to have it hit an unmoving target. The first hit gets registered, but the next do not unless I move either the static target (by pushing it) or the player itself.

Both the hitbox and the hurtbox have kinematic rigidbodies in them. They are separate BoxCollider2Ds in their own "Hitbox" and "Hurtbox" layers, which only interact between themselves. My hit detection code is as follows:

void OnTriggerEnter2D(Collider2D col) {
Debug.Log(col + " got hurt");
}


Here's a graphical example of what's going on. You can see how hit detection doesn't work until I nudge Test Monster. When I try to attack it without moving it, detection stops working.

• That first option might work, but I've seen the way I'm doing it work in some tutorials online, that's why it bothers me so much. I bet the problem is OnTriggerEnter doesn't register when a trigger spawns into a collision... but I haven't seen that documented anywhere. I'll try that, but I'm still on the lookout for the reason as to why this doesn't work. Thanks for the suggestion, though. – Karv Jun 11 '17 at 16:03

OK, after a bit of tinkering, my brother and I finally found the answer.

The issue is as follows: Enabling/disabling a BoxCollider (or any collider for that matter) doesn't wake up the RigidBody to which it's attached, but movement does. That's why it only worked when moving.

All we needed is to make the Game Object's RigidBody2D to "Never Sleep". It's as simple as that.

You might try using OverlapArea instead of creating separate colliders for your hitboxes. That approach might make your code cleaner too, since you'd be detecting hits in the same place that the hitbox is activated, rather than a separate OnTrigger function.

The OnTriggerEnter2D only works when you enter for the first time then it will only work again when you exit the Trigger and re-enter so what who should use is:

void OnTriggerStay2D(Collider2D col)
{
Debug.Log(col + " got hurt");
}


OnTriggerStay2D will work while you are inside the trigger.

The Problem is that it will be sending a Debug Log while you are inside

So you need to add some kinda of if statement like this

void OnTriggerStay2D(Collider2D col)
{
if (Input.GetMouseButton(0))
{
Debug.Log(col + " got hurt");
}
}


Change if statement depending on what key you want to use to attack.

if OnTriggerStay2D doesn't work well alone try using both OnTriggerStay2D and OnTriggerEnter2D. Also this code

void OnTriggerEnter2D(Collider2D col)
{
Debug.Log(col + " got hurt");
}


will always send got hurt even if you are attacking or not so who should add a if statement like this

if (Input.GetMouseButton(0))
{
Debug.Log(col + " got hurt");
}