It’s been perfectly effective to do exactly what I want, but of course, this means that the value keeps changing the longer the scene is running. I’m not super concerned for its efficiency at this time, but I don’t want to shoot myself in the foot.
All that “wait for X seconds and then do this and that” kind of stuff can be managed pretty nicely using Coroutines!
You write something like this:
IEnumerator YourTimedCommand() {
SomeCommand();
// execution will pause here and return to the same point
// after 0.5 Seconds, without pausing any other scripts.
yield return new WaitForSeconds(.5f);
SomeLateCommand();
}
And then start it using StartCoroutine():
StartCoroutine("YourTimedCommand");
That even works with loops and all that and as soon as the bottom of your method is reached, the coroutine stops. So you could either run an endless loop until some condition is fullfilled or just have one “async” method with some delays in it, depending on what you need, it’s pretty usefull
I think it could be a bit simpler. I wouldn’t have so many operands at once because if one condition is not true, you won’t have to check the others. A simple way to measure time, you can do:
public float fireRate;
private float lastShot;
void Update()
{
if ( Input.GetMouseButton( 0 ) )
{
Shoot();
}
}
void Shoot()
{
if ( lastShot + fireRate < Time.time )
{
// Pool or instantiate your bullet
// Set whatever properties you need
// Fire it off
lastShot = Time.time;
}
}
If you’re afraid of the number constantly increasing you can do it a different way.
public float fireRate;
private float lastShot;
private float defaultFireRate;
void Awake()
{
defaultFireRate = fireRate;
}
void Update()
{
if ( fireRate <= 0 )
{
if ( Input.GetMouseButton( 0 ) )
{
Shoot();
}
}
else
{
fireRate -= Time.deltaTime;
}
}
void Shoot()
{
// Pool or instantiate your bullet
// Set whatever properties you need
// Fire it off
fireRate = defaultFireRate;
}
Coroutines are great but not the best for constantly changing values. They also generate garbage, so use them only when needed.
Personally, I believe the best option is to create Timer class and use that to set/check time for your game…