Home > Back-end >  Is my way using coroutine in Unity wrong?
Is my way using coroutine in Unity wrong?

Time:11-24

Im using coroutine to make a little break that's reloading the bullet. I don’t know why this doesn’t work, which is to say, there is no time waiting. I’m probably not using the coroutine correctly. Can somebody help me?

if (Input.GetMouseButton(0) && Time.time > nextFire && !inventoryInterface.activeSelf)
{
    //aimAnimator.SetTrigger("Shoot");
    nextFire = Time.time   fireRate;
    if (count < gun.bulletsInAMagazine)
    {
        Vector3 mousePosition = UtilsClass.GetMouseWorldPosition();
        OnShoot?.Invoke(this, new OnShootEventArgs
        {
            gunEndPointPosition = aimGunEndPointPosition.position,
            shootPosition = mousePosition
        });
        count  ;
    }
    else
    {
        count = 0;
        StartCoroutine(FireCooldown());
        Debug.Log("Reloading");
    }
    //StartCoroutine(FireCooldown());
    //allowFire = true;
}

And the enumerator:

IEnumerator FireCooldown()
{
    yield return new WaitForSeconds(gun.reloadTime);
}

CodePudding user response:

IEnumerator FireCooldown()
{
    yield return new WaitForSeconds(gun.reloadTime);//check that gun.reloadTime is not null                         
                                                                    
     // and type here the method that you want to run after reloading
}

CodePudding user response:

You need to change the allowFire bool to true inside the couroutine

IEnumerator FireCooldown()
{
    yield return new WaitForSeconds(gun.reloadTime);
    allowFire = true;
}
  • Related