Laser Defender - Fire Repeatedly Coroutine not working

Hi,

I followed along the lecture where we change the code to fire projectiles repeatedly when spacebar is pressed down and stop firing when we let go off the spacebar.

I have compared with the code given against the lecture and also dug through the Q & A section of Udemy, but I quite cannot figure out why the projectiles are not firing repeatedly when I hold the spacebar down rather it is just firing one at a time each after 0.1f seconds have elapsed. Any help is appreciated :slight_smile:

Player.cs

    [SerializeField] float projectileFireDuration = 0.1f;
    Coroutine fireRepeatedlyCoroutine;

     void Update()
    {
        MovePlayer();
        FireLaser();
    }

    private void FireLaser()
    {
        if(Input.GetButtonDown("Fire1"))
        {
            fireRepeatedlyCoroutine = StartCoroutine(FireRepeteadly());
        }

        if(Input.GetButtonUp("Fire1"))
        {
            StopCoroutine(fireRepeatedlyCoroutine);
        }
    }

    IEnumerator FireRepeteadly()
    {
        while (true)
        {
            GameObject laser = Instantiate(playerLaserPrefab, transform.position, Quaternion.identity);
            laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectileSpeed);
            yield return new WaitForSeconds(projectileFireDuration);
        }
    }

Input Manager in my Project Settings

I donโ€™t understand the issue. Are you trying to say that it only fires once when you press the spacebar? Because what you described is exactly the behavior you coded: Fires one at a time each after 0.1f seconds have elapsed.

1 Like

Hi,

Sorry the projectileFireDuration in my code was a bit longer leading to the above mentioned behaviour.

Thanks anyway!

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

Privacy & Terms