Корутины в Unity

Данный объект должен атаковать один раз в полторы секунды. Но он делает это чаще. В чем ошибка?

public float strong = 7f;

private void OnTriggerStay(Collider other)
{
    if (other.gameObject.name == "Player")
    {
        StartCoroutine(Attack(other.gameObject));
        Debug.Log("wa");
    }
}
    

IEnumerator Attack(GameObject player)
{
    if (player.GetComponent<PlayerMove>().health > 0.0f)
    {
        player.GetComponent<PlayerMove>().health -= 7f;
        yield return new WaitForSeconds(1.5f);
    }
    Debug.Log("wa");
}

Ответы (1 шт):

Автор решения: Yaroslav

При каждом OnTriggerEnter ты запускаешь ещё одну корутину, их может быть сколько угодно.

private IEnumerator _attackCoroutine;

private void OnTriggerEnter (Collider other)
{
    if (_attackCoroutine == null && other.TryGetComponent(out PlayerMove playerMove))
    {
        _attackCoroutine = AttackCoroutine(playerMove, 7, 1.5f);
        StartCoroutine(_attackCoroutine);
    }
}

private void OnTriggerExit (Collider other)
{
    if (_attackCoroutine != null && other.TryGetComponent(out PlayerMove playerMove))
    {
        StopCoroutine(_attackCoroutine);
        _attackCoroutine = null;
    }
}

private IEnumerator AttackCoroutine (PlayerMove playerMove, float damage, float delay)
{
    // с if это будет происходить только 1 раз
    while (playerMove.health > 0)
    {
        playerMove.health -= damage;
        yield return new WaitForSeconds(delay);
    }
    _attackCoroutine = null;
}
→ Ссылка