Attack Timer Out of Wack

I’ve been slowly learning C# and have been using tutorials and researching code examples to put together a script for 2D attacks. Everything seems like it’s working great except that the attacks aren’t executing immediately after they’re triggered.

I believe that my Attack Time is the issue, as I have the if statement saying that if the attackTime <= 0, then attack and reset the timer to startTimeAttack (0.5). The problem is that I rarely see the attackTime value reach <= 0, but it is clearly on a quick loop because I’ve serialized the value and see that it is constantly changing values between 0 to 0.5.

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

public class NewAttack : MonoBehaviour
{

    Animator animator;

    public float attackTime;
    public float startTimeAttack;

    public Transform attackLocation;
    public float attackRange;
    public LayerMask enemies;

    // Start is called before the first frame update
    private void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (attackTime <= 0)
        {
            if (Input.GetButton("Fire1"))
            {
                animator.SetBool("isAttacking", true);
                Collider2D[] damage = Physics2D.OverlapCircleAll(attackLocation.position, attackRange, enemies);

                for (int i = 0; i < damage.Length; i++)
                {
                    Destroy(damage[i].gameObject);
                }
            }
            attackTime = startTimeAttack;
        } else
        {
            attackTime -= Time.deltaTime;
            animator.SetBool("isAttacking", false);
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(attackLocation.position, attackRange);
    }
}

Any advice here? Not sure if I am approaching this the right way or not. Thank you

Looks solid… almost… so close! ALMOST a textbook implementation of a cooldown timer!

But one bug: line 38 should most likely be up one line so that it ONLY gets set to attack time when you hit FIRE.

Here’s more:

Cooldown timers, gun bullet intervals, shot spacing, rate of fire:

GunHeat (gunheat) spawning shooting rate of fire:

1 Like

Solved! You’re awesome thanks so much!

1 Like