Why use loop in attack

i’ve gone through several tutorials over 2d attacks. basically they involves looping through the array of enemies detected by overlapcircle, but i have a question
if, say, the TakeDamage is called x times due to x number of enemies, doesnt that mean an “enemy” gets hit x times?

Your question is too vague. Without seeing the code we can’t really tell what the code actually does. If you use OverlapCircle to get a list of enemies, the for loop probably will iterate through the enemies and call TakeDamage once on each of those enemies I would assume. But your hypothetical is not clear.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerAttack : MonoBehaviour {

    private float timeBtwAttack;
    public float startTimeBtwAttack;

    public Transform attackPos;
    public LayerMask whatIsEnemies;

    public float attackRange;
    public int damage;

    void Update() {
        if (timeBtwAttack <= 0) {
            if (Input.GetKey(KeyCode.Space)) {
                Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPos.position, attackRange, whatIsEnemies);
                for (int i = 0; i < enemiesToDamage.Length; i++) {
                    enemiesToDamage[i].GetComponent<Enemy>().TakeDamage(damage);
                }
            }
            timeBtwAttack = startTimeBtwAttack;
        } else {
            timeBtwAttack -= Time.deltaTime;
        }
    }
}

im sorry this is an example

Each enemy within attackRange only gets damage taken off once, check the for loop:

for (int i = 0; i < enemiesToDamage.Length; i++) {
                    enemiesToDamage[i].GetComponent<Enemy>().TakeDamage(damage);
                }

enemiesToDamage[i] is only one enemy in the array, so it does TakeDamage() once to each.

1 Like

thank you i didnt see it be4