按住开火键,每隔一定时间连续发射子弹

Fire bullets at an interval continuously while the fire button is held down

在 C# Unity3D 中,我试图让我的子弹以 bulletTime 的间隔发射。目前单发效果很好,但是当我按住开火按钮时,只创建并发射了 1 颗子弹,然后没有其他任何反应。

// Left mouse button HELD down.
else if (fireAgain && Input.GetMouseButton(0)) 
{   
    StartCoroutine("LoopNShoot");
    fireAgain = false;
}
else if (timerH < bulletTime)
{
    timerH += Time.deltaTime;

    if(timerH >= bulletTime)
    {
        fireAgain = true;
        timerH = 0;
    }
}   
    

IEnumerator LoopNShoot()
{
    pivot.transform.Rotate(triggerAngle,0,0);
        
        GameObject bullet = ObjectPooler.SharedInstance.GetPooledObject(); 
        if (bullet != null) {
                bullet.transform.position = SSpawn.transform.position;
                bullet.transform.rotation = SSpawn.transform.rotation;
                bullet.SetActive(true);
         }

    yield return new WaitForSeconds(.1f);
            pivot.transform.rotation = Quaternion.Slerp(transform.rotation, originalRotationValue, Time.deltaTime * rotationResetSpeed); 
    
}

我想我需要将我所有的 if 语句和计时器放在协同程序中吗?但这似乎也无济于事...

请忽略枢轴和旋转,它对某些动画效果很好,唯一不起作用的是在按住开火按钮的同时以设定的间隔连续发射子弹。

你应该删除这些 else 然后就可以了。

private void Update()
{
    if (fireAgain && Input.GetMouseButton(0)) 
    {   
        StartCoroutine("LoopNShoot");
        fireAgain = false;
        timerH = 0;
    }

    if (timerH < bulletTime)
    {
        timerH += Time.deltaTime;

        if(timerH >= bulletTime)
        {
            fireAgain = true;
        }
    }   
}

您也可以重新排列它以使其更清楚它是如何工作的:

private void Update()
{
    if(!fireAgain)
    {
        timerH += Time.deltaTime;

        if (timerH >= bulletTime)
        {
            fireAgain = true;
        }         
    }
    else
    {
        if(Input.GetMouseButton(0)) 
        {   
            StartCoroutine("LoopNShoot");
            fireAgain = false;
            timerH = 0;
        }
    }       
}

其实我以为你已经选择了我给你看的Invoke方法