Home > Back-end >  Shooting cooldown for enemy in unity2d
Shooting cooldown for enemy in unity2d

Time:05-22

I'm doing a top-down shooter in unity, I'm trying to make the enemy shoot when it sees the player. So far, this is my code:

public class EnemyShooting : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;
    public float bulletForce = 20f;
    public FieldOfView _fieldofview;
   
        void Start()
    {
        _fieldofview = FindObjectOfType<FieldOfView>();
    }

    // Update is called once per frame
    void Update()
    {
       if(_fieldofview.canSeePlayer)
       {
           Shoot();
       }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();

        rb2d.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
    }
}

However, when the player is detected it just spams the bullets due it doesn't has a cool down timer. I've tried with a Coroutine and the Invoke method but it doesn't works. Any ideas?

CodePudding user response:

The following code defines two times. The current cooldown and shoot cooldown. Add the bottom and your problem will be solved.

public float shootCooldown = 5; // 5sec for e.g.
private float currentCooldown;

void Update()
{
    if (currentCooldown > 0) // If shoot not in cooldown
    {
        currentCooldown = shootCooldown; // Set current cooldown time to shootCooldown
        if(_fieldofview.canSeePlayer) Shoot();
    }
    else currentCooldown -= Time.deltaTime; // Reduce cooldown over time
}
  • Related