c# - "Bool" changes but "if" doesn't work correctly - Stack Overflow

admin2025-04-29  3

I'm making a game in Unity 2D, the _isAttacking variable becomes true during an attack, and after the attack it becomes false, after which (if the player is still in the attack zone) it instantly becomes true, but neither the animation nor everything else is played again. All relevant points have been marked with comments.

void Update()
{
    if (distanceToPlayer <= chaseRadius && !_isAttacking)
    {
        isMoving = true;
        ChasePlayer();
    
        if (distanceToPlayer <= attackRange)
        {
            _isAttacking = true; // When the attack starts, the variable becomes true
            isMoving = false;
            rb.velocity = Vector2.zero;
            anim.SetBool("isMoving", false);
            anim.SetTrigger("Attack");
            Attack(); // Launch attack
        }
    }
    else
    {
        isMoving = false;
        rb.velocity = Vector2.zero;
        anim.SetBool("isMoving", false);
    }
    anim.SetBool("isMoving", isMoving);
}
    
    
private void Attack()
{
    if (Time.time > _nextAttackTime)
    {
        _nextAttackTime = Time.time + attackCooldown;
        if (Vector2.Distance((Vector2)transform.position + offset, player.position) <= attackRange && _player != null)
        {
            _player.TakeDamage(attackDamage);
            Debug.Log("A zombie has damaged a player!");
        }
        _isAttacking = false; // Here _isAttacking becomes false, Debug.Log also works correctly
        Debug.Log(_isAttacking);
        //anim.ResetTrigger("Attack");
    }
}

I did checks using Debug.Log and they showed that the variable actually becomes false after the attack, and also immediately becomes true after that, but the rest of the code is not executed. Also at the very end I have a commented line anim.ResetTrigger("Attack") I tried uncommenting it, but it did not solve the problem. Repeat is turned off on my attack animation. The rest of my code is not relevant to the problem, so I removed it to make it easier to find the problem, but I can attach the full code if necessary.

This is what my transitions between animations look like

idle -> walk when isMoving = true

walk -> idle when isMoving = false

any state -> attack (trigger "Attack")

转载请注明原文地址:http://anycun.com/QandA/1745941437a91427.html