(New User) Need an alternative to foreach loop


I need a substitute for the foreach loop on line 111 there. I’ve tried controlling it so that it only damages the player’s health once with variables but there always seems to be a moment where the “HasAttacked” bool is false while the loop is running and it ends up either instagibbing my player or not dealing damage at all.

Is there a substitute for the foreach in this case that will only instantiate once? If so, what’s it called and how exactly do I enter it so that it accounts for my player? I’ve looked around for a few hours now and haven’t found a way to just trigger one instance of damage via an overlap circle.

Thanks!

Hey,

Hopefully I’m looking at this properly. I’m honestly a little confused by the way you’ve set things up, but if you only have one player, you shouldn’t need to use a foreach loop at all.

Instead of using Physics2D.OverlapCircleAll(), you can just use Physics2D.OverlapCircle(). This will get a single Collider2D instead of an array.

Example:

        Collider2D hitPlayer = Physics2D.OverlapCircle(attackPoint.position, attackRange, playerLayers);

        if (HasAttacked == false && hitPlayer != null)
        {
            HasAttacked == true;
            player.GetComponent<Health>().TakeDamage(attackDamage);
        }

If I misunderstood something, please let me know.