plz help burst fire script

hi,

i am trying to make a burst fire script in javascript. i want it to:

hold ‘space’ it will fire a number of shots, pause for a period of time, and repeat until ‘space’ is released.

i have tried many different things but nothing has worked. right now when unity starts up it will fire three shots, wait a second and then fire for infinity without ever hitting a button. please help!

function Start()

{

	if(Input.GetButton('Jump'))

	{

		canShoot = false;
		
		for(var i = 0; i < 3; i++)
		{
			if(i == 3)
			{
				canShoot = false;
				yield WaitForSeconds (3.0);
			}
			else
			{
				canShoot = true;
                yield WaitForSeconds (1.0);
                canShoot = false;
                yield WaitForSeconds (1.0);
			}
		}
	}
}
function Update()
{
	if(canShoot == true)
	{    
       // instantiate
	}
}

One issue I see is that you’ve put your shooting code into a Start function.

I haven’t tested this code so if it doesn’t work just tell me.

Try this:

function burstFire()
{
		for(var i = 0; i < 3; i++)
	{
		if(i == 3)
		{
			canShoot = false;
			yield WaitForSeconds (3.0);
		}
		else
		{
			canShoot = true;
			yield WaitForSeconds (1.0);
			canShoot = false;
			yield WaitForSeconds (1.0);
		}
	}
}
	   
function Update()
{
	if(Input.GetButton('Jump'))
	{
		canShoot = false
		burstFire();
	}
		
    if(canShoot == true)
    {    
       // instantiate
    }
}

As Althaen suggested, you should move this logic out of your Start method and into Update. However, I think your logic is slightly off. This is tricky to get right, and I definetly didn’t get it my first shot. Let me walk you through my solution (tested and working).

In the code below, we check if the user presses the button and that we aren’t already firing bursts. If so, we record that they are holding the key (in the firing variable) and start a coroutine. While they keep holding the key, the coroutine will loop through instantiating three bullets (with a short delay), then waiting. When the user stops holding the key, the coroutine will finish its current burst, then stop. (If you want it to stop halfway through a burst you could add if (!firing) break; before the calls to shoot();

var firing = false;

function burstFire() {
    while (firing) {
        shoot();
        yield WaitForSeconds(0.2);
        shoot();
        yield WaitForSeconds(0.2);
        shoot();
        yield WaitForSeconds(3.0);
    }
}

function shoot() {
    // instantiate
    Debug.Log("shoot!");
}

function Update () {
    if (Input.GetButton('Jump') && !firing) {
        firing = true;
        burstFire();
    }
    
    if (!Input.GetButton('Jump')) {
        firing = false;
    }
}