Hi, I have a problem with the Hitboxes of some enemies. Out of necessity I added two
Box Collider 2Ds to a enemy (one to make it collider into walls and other objects, except the other enemies and the Player, the other to damage the Player with a
OnTriggerEnter) however when I try to hit them they receive double the damage. Enemies with multiple Hitboxes due to their size and shape also have the same effect too. The code provides the Player with the ability to attack multiple enemies at once with a single attack. So how do I fix it? I’m new to Unity and I’m not sure what to do.
Thanks in advance
Instantiate(taglioDea, attackPoint.position, attackPoint.rotation, attackPoint); //
Collider2D hitNemici = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, nemiciLayers);//Nemici = enemy
foreach (Collider2D nemici in hitNemici) // hits all enemies that are in the attack hitbox and subtracts damage
nemici.GetComponent<Nemici>().DannoEffettivo(dannoTaglio); // enemy take damage
nemici.GetComponent<Contracolpo>().ContraColpoEffettivo(attackPoint); // enemy take knockback
Some parts of the code are written in Italian… hope you understand anyway
It looks like the problem is related to you having multiple colliders. Having more than collider makes it can register multiple times and cause double damage. One way to solve it to use Unity’s layers and tags to categorize different objects in your game. For example, set a specific layer for enemies, the player, and other objects.
Check out: https://learn.unity.com/tutorial/intro-to-the-unity-physics-engine-2019-3
What I usually do that I have the trigger handling class (the monoBehaviour that receives the OnTriggerEnter/Exit events) retrieve the actor that entered it (the player / damage receiver, not the collider) and store it in a dictionary with its Value being the number of enters. So if a second collider enters the trigger, it just adds its entry count. Same when exiting, every time a collider exists the trigger, I remove one from the Value (until it reaches zero, when I remove the whole actor key from the dictionary). That way you can easily track what actors are inside the trigger and when do they enter with the first collider.
To handle that, I’d usually have some abstract MonoBehaviour class called Actor (or Entity, but recently it’s getting confused with ECS entities) and when a collider enters/exits, i use