Implementing shooting on hold without disabling second input button

Hey guys, I want to share my solution for the problem from this lecture which doesn’t have the bug when the fire just won’s stop when you’re using both of your input buttons. It also doesn’t include StopCoroutine() or StopAllCoroutines() methods:


''''
public class Player : MonoBehaviour
{
    ''''
    private bool mayFire = true; //indicates whether a player's ship is allowed to shoot another bullet (sorry for the alignment now and further)

    ''''    
    void Update()
    {
        Move();
        if(mayFire) //if a player is allowed to shoot, then give him such opportunity

        StartCoroutine(FireContinuosly());
    }

    private IEnumerator FireContinuosly()
    {
        if (Input.GetButton("Fire1"))
        {
           GameObject laser = Instantiate(laserPrefab, 
            transform.position, Quaternion.identity) as GameObject;
           laser.GetComponent<Rigidbody2D>().velocity = 
                                                new Vector2(0, projectileSpeed);
        }

        mayFire = false; //when a player shoots, he's disallowed to shoot again for some tiny moment (to prevent "rapid firing")

        yield return new WaitForSeconds(projectileFiringSpeed);

        mayFire = true; //and when that moment passes, player's allowed to shoot again

    }

    ''''
}

I only left the code that was different from Rick’s solution, marking everything else with ‘’’’.

If you see any lack of this solution I didn’t notice, please tell me about it.

I actually just got to this course lesson myself, and I came up with a bit of a simpler solution to it. My idea was to just put an if statement to check if there already was a firing coroutine running, and if so, to stop it. I tested it out a bit and it seems to work without issues, but please let me know if there’s something wrong with this idea:

private void Fire()
    {

        if (Input.GetButtonDown("Fire1"))
        {
            if (firingCoroutine != null)
            {
                StopCoroutine(firingCoroutine);
            }
            firingCoroutine = StartCoroutine(FireContinuously());
        }
        if (Input.GetButtonUp("Fire1"))
        {
            StopCoroutine(firingCoroutine);
        }
    }
3 Likes

Minor Suggestion, so the ship keeps firing until both buttons are released:

private void Fire() {

        if (Input.GetButtonDown("Fire1") && (fireCorutine == null))

        {

            fireCorutine = StartCoroutine(FireCoroutine());

        }

        

        if (Input.GetButtonUp("Fire1") && !Input.GetButton("Fire1"))

        {

            StopCoroutine(fireCorutine);

            fireCorutine = null;

        }

    }

It worked well in my game, thanks for the idea.

Thanks! it’s working.

Privacy & Terms