Hi there,
I decided to setup my autofire system in a slightly different way to Rick by using a lock (like a basic semaphore, if you prefer - StackOverflow - What is a semaphore?) that limits when the co-routine can fire, rather than just toggling constant firing on and off.
So I’ve got the following in my class properties:
[SerializeField] float shotsPerSecond = 10.0f;
float shotDelaySeconds;
bool shotTimerExpired = true;
Then in Start() we set the shotDelaySeconds (a bit more human-friendly than specifying fractions of a second) as:
shotDelaySeconds = 1.0f / shotsPerSecond;
In the Update() method we check whether we should fire and then whether we can fire with:
// While any 'fire' key is being held...
if (Input.GetButton("Fire1"))
{
// If we are able to shoot...
if (shotTimerExpired)
{
// ...call our ShootLaser co-routine which allows us to fire a laser, but
// then 'sets the lock' until the shot timer expires and we can shoot again.
firingCoroutine = StartCoroutine(ShootLaser());
}
}
And finally the co-routine itself is then:
IEnumerator ShootLaser()
{
// If the shot timer has expired then we can fire...
if (shotTimerExpired)
{
// Lock the co-routine and fire
shotTimerExpired = false;
GameObject laser = Instantiate(laserPrefab, this.transform.position, Quaternion.identity) as GameObject;
laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0.0f, projectileSpeed);
}
// Do the code below after a short period of time
yield return new WaitForSeconds(shotDelaySeconds);
// Unlock the co-routine after the above delay so we can fire again
shotTimerExpired = true;
}
Just thought I’d post this here in-case it might be of use to anyone!
Cheers!
P.S. Loving the course, Rick! =D