Burst Fire -Laser Defender-

Hey People,

This is the block for firing projectiles as we did it in the laser defender lecture.

private void Fire()
{
    if (Input.GetButtonDown("Fire1")) 

    {
        rapidFireCoroutine = StartCoroutine(RapidFire());
        animatorMuzzleFlash.SetFloat("Muzzle", 0.6f);
    }
    if (Input.GetButtonUp("Fire1"))
    {
        StopCoroutine(rapidFireCoroutine);
        animatorMuzzleFlash.SetFloat("Muzzle", 0.4f);
    }
}

IEnumerator RapidFire()
{
    while (true)

     { 
        
    
        GameObject laser = Instantiate(laserBeam, firePosition.position, Quaternion.identity) as GameObject;
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
    

    yield return new WaitForSeconds(projectileFiringPeriod);

    }
    
}

This block instantiates a projectile when the fire button is down, waits for a chosen period, and instantiates another until the fire button is up.
Now I would like to modify this code block to add different firing modes. The first thing I thought was to add a for-loop at the top to have a burst fire mode, but it did not change the outcome. This is the modified block.

IEnumerator RapidFire()
{
while (true)

     { 
        for (int i = 0; i < 5; i++)
    {
        GameObject laser = Instantiate(laserBeam, firePosition.position, Quaternion.identity) as GameObject;
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
    }

    //animatorMascineGun.SetFloat("Fire", 0.6f);
    yield return new WaitForSeconds(projectileFiringPeriod);

    }
    
}

Doesn’t the second block mean: Instantiate 5 projectiles and then wait for a period, and Instantiate 5 more until the fire button is up? To be more precise, when we get into the while loop and come to the for loop, shouldn’t it run the code inside the for-loop until i < 5 is not true(so 5 times in this case) before running the yield line?

1 Like

Yes, that’s exactly what it does, but there’s an issue, your code will instantiate the missiles pretty much at the same time making them look like there’s only one missile instead of 5. To check if my theory is correct, fire, pause the editor and check your hierarchy, there should be 5 new objects.

If all of this is true and you want the missiles to have a gap between them you’ll have to add a new WaitFor inside the FOR loop.

You were right ofc…=) A bit silly of me not to get what was wrong…Thanx mate…=)

1 Like

Glad I was able to help, and worry not, it happens to all of us.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms