- Home /
Finding the exact time in a WaitForSeconds that it is currently at
In my game I have a coroutine that times when my bad guys fire. It works using a min and max random number everytime. The problem that I am having is that I need to deactivate the bad guys when I pause. As I understand it a coroutine will not resume after being deactivated. What I was thinking I would do (assuming this is possible) is to use OnDisable to find out where in the WaitForSeconds timer the coroutine is at when it is deactivated and then use OnEnable to input that into the coroutine. The issue that I have now is if the player pauses the game within the minimum amount of time the bad guys could shoot they can prevent them from shooting at all.
Answer by hackisacker · Jan 05, 2018 at 05:23 PM
I just now saw your reply. Here is what I got working.
private float shootTimer;
private float shootTimerRemaining = 0;
IEnumerator waitSpawn()
{
while (shootTimerRemaining < shootTimer)
{
shootTimerRemaining = shootTimerRemaining + .5f;
if (shootTimer < shootTimerRemaining){
shootTimer = Random.Range(minWait, maxWait);
LaunchProjectile();
shootTimerRemaining=0;
}
yield return new WaitForSeconds(.5f);
}
}
Then OnEnable() I just call the coroutine again and it resumes where it left all the only problem with this is that it updates every half second. Not sure if it is the most efficient method but my game is pretty simple so this works for me.
Answer by Creatom_Games · Jan 05, 2018 at 02:10 AM
I have an idea, it involves a while-loop. You initialize three variables, one which tells you how much time you wait, one as an iterator variable(i for example), and the other which keeps track of which iteration you are at. use the while loop keep repeating the WaitforSeconds command to wait one second. You also use the loop to set the variable which keeps track of the current iteration to i. That way, you can use i to tell which second the reload function is at. Now, in the OnDisable function, you can grab the how-much-time-you-wait variable and the current-iteration variable which represents which time the waitforseconds is at.
int randomreload = Random.Range(whatever, whatever);
int i = 0;
int track = 0;
while (i < randomreload){
track = i;
yield return new Waitforseconds(1);
}
//in your OnDisable function, just grab randomreload and track
The only thing I am worried about is the yield return statement, I forgot if it will begin and the start of the function and not the loop.