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?

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 ) ) ;
}

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.