How can I remove 1every second from integer A while bool B is true?
I am trying to script a generator that uses up one fuel when it is on every second.
The script I tried to use:
public IEnumerator usingfuel()
{
while (generatorOn == false)
{
yield return null;
}
yield WaitForSeconds(10);
fuelcount -= 1;
}
Why does it not work and how can I improve it?
Answer by Hellium · Jul 31, 2018 at 04:41 PM
Try this (not tested)
public IEnumerator usingfuel( float interval )
{
float timer = interval ;
while( true )
{
if( generatorOn )
{
timer -= Time.deltaTime ;
if( timer < 0 )
{
fuelcount -= 1 ;
timer = interval
}
}
yield return null
}
}
You will have to run this coroutine once, from the Start
function for instance.
void Start()
{
StartCoroutine( usingfuel( 10 ) ) ;
}
Answer by MacDx · Jul 31, 2018 at 04:40 PM
There are various problems with this code.
First, it won't even compile because yield WaitForSeconds(10); is syntactically wrong. This is the correct syntax
yield return new WaitForSeconds(10);
Second, you say you want to decrease fuel every second but you are passing a 10 to WaitForSeconds instead of 1?
Third, this coroutine will only decrease fuel once and then stop, I don't know if you are starting it multiple times but that would be bad since it defeats the point of having a coroutine in the first place (which is to have something run continuously and in "parallel" to Update).
This is how I'd do it:
public IEnumerator UsingFuel()
{
while(!gameOver)
{
if(generatorOn)
fuelcount --;
yield return new WaitForSeconds(1f);
}
}
Notice that I added an extra bool. This way you just start this coroutine at Start, and if you change generatorOn to true or false it will just work. And if you want to stop it then you just set gameOver to true.
Hope this helps.
A very skilled player could prevent the fuel from decreasing if he / she releases the button responsible for turning on generatorOn
only when the coroutine "ticks" at t = 0, t = 1, t = 2, ....
Yeah, if generatorOn is tied to to input then yes, but we don't know that.
Your answer

Follow this Question
Related Questions
How to use IEnumerator? Pls help! 1 Answer
reload script assemblies is VERY Slow. 1 Answer
Using rb.velocity causes low gravity. 2 Answers