- Home /
OverlapCircleAll detects too many collisions
Hi, i'm trying to make some melee combat. I've got a player with a script where I use OverlapCircleAll to detect enemy colliders and print their names after an attack input is given. Then I have an enemy prefab made up of just a Rigidbody2D and a BoxCollider2D. I have assigned the enemy to a dedicated enemy layer (enemyLayers) which I gave to the OverlapCircleAll function in the player script. The problem is that when I hit the enemy its name is printed not one but like 500 times and causes lag. I imagine the function is just detecting multiple collisions with the same object but dont know how to fix it. Thank you in advance.
This is the function I call every time the input is given: 
And here are the components of the enemy 
Answer by Llama_w_2Ls · Apr 30, 2021 at 02:58 AM
You can add any hit enemies to a list, then check whether the list already contains your enemy before completing an action with it. E.g:
IEnumerable<GameObject> Enemies;
void Punch()
{
var cols = Physics.OverlapSphereAll(pos, range);
if (Enemies == null)
Enemies = cols;
var enemies = cols.Where(x => !Enemies.Contains(x));
foreach (var newEnemy in Enemies)
{
// Do smt with the unique enemy once
}
}
Its important to refresh the list every time you punch again Hope that helps
Answer by FraTach03 · Apr 30, 2021 at 05:52 PM
I found all I had to do was setting a time to wait between each attack. Splatting my face for you right now. Thanks for your time anyway.
Your answer