I’m making a game where when you swing your sword, it enables a trigger boxcollider2d for the hit area of the sword swing, which damages enemies through OnTriggerEnter2D, and then disables after a few seconds. If i approach an enemy, stay still and swing, the first time it will hit the enemy and OnTriggerEnter2D is called, but if I swing again (that is, the same collider is disabled and enabled again through code), OnTriggerEnter2D is not called, and I have to back up to try and hit it again for some reason. But if I do exactly what the code is doing through the inspector, I.E., stay still and turn the collider on and off again, OnTriggerEnter2D is called and everything works as intended. Why is that?
If you enable the collider the first time, check for something in the range and when found, disable it…you are not clearing the collider’s memory of interacting with the object. It means that even when you reenable it, it will not start at a default state and think that the object is still inside the collider, resulting in
- The problem you are facing - Since the collider thinks that the object is still interacting with it, it will not fire OnTriggerEnter() again, which means that it will not execute the code once again. When you back away and try again, OnTriggerExit() is called once and then the collider gets ‘reset’ in simple terms. Why does turning it on and off through the inspector works, idk.
- It can also cause OnTriggerExit() not being called if you have moved the collider away from the object after disabling it.
Can you Share you code so i can properly suggest corrections an improvement. Thanks.