简体   繁体   中英

How do I loop a command in Unity for a specified amount of time

I am trying to make an attack script for the player in unity. The attack would work by creating a transform in front of the player and when the player pressed the attack button, a one second timer would be started where any enemies that entered the transform would be killed. After the timer ended the enemies wouldn't be killed anymore when entering the transform. I tried to do that by looping the essential command for killing the enemies for one second using the InvokeRepeating command. However I never used it before so of course it didn't work. I have to mention that I used StartCoroutine to make the command repeat for one second. I apologize for my lack of knowledge as I am new to Unity and programming. Anyway here is the code:

public class PlayerAttack : MonoBehaviour
{
    public Transform AttackArea;
    bool IsAttacking = false;
    public Animator animator;
    public LayerMask EnemyLayers;
    public float AttackRange = 0.5f;
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {

            animator.SetTrigger("Attack");
            StartCoroutine(AttackLoop());
            Attack();
            InvokeRepeating("Attack", 0, 0);
        }
    }


    void Attack()
    {

            Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackArea.position, AttackRange, EnemyLayers);
            foreach (Collider2D enemy in hitEnemies)
            {
                enemy.GetComponent<Enemy_1>().Death();
            }

    }
    


    void OnDrawGizmosSelected()
    {
        if (AttackArea == null)
            return;
        Gizmos.DrawWireSphere(AttackArea.position, AttackRange);

    }
    IEnumerator AttackLoop()
    {
        yield return new WaitForSeconds(1);
        {
            CancelInvoke("Attack");
        }
    }



}

A simple way is to create a single coroutine that tracks time using Time.deltaTime and loops until the appropriate time has elapsed:

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        StartAttack();
    }
}

void StartAttack()
{
    float attackDuration = 1.0f; // attack for 1 second
    animator.SetTrigger("Attack");
    StartCoroutine(AttackLoop(attackDuration));
}

void Attack()
{
    Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackArea.position, AttackRange, EnemyLayers);
    foreach (Collider2D enemy in hitEnemies)
    {
        enemy.GetComponent<Enemy_1>().Death();
    }
}

IEnumerator AttackLoop(float attackDuration)
{
    float elapsedTime = 0f;
    while (elapsedTime < attackDuration) 
    {
        Attack();
        yield return null;
        elapsedTime += Time.deltaTime;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM