Toggling bools automatically using coroutines

Hello all,

Just a quick question from a programming noob.

I have encountered many situations where a bool needs to turn itself on or off after a given amount of time and so I thought I could make a coroutine that can act as a switch for any bool. Here is what I tried:

IEnumerator ToggleBool (bool thebool, float time)
		thebool = true;
		yield return new WaitForSeconds(time);
		thebool = false;

Here is how this would be used in Update:

if (firsttextdelay - Time.deltaTime >= 5)
			StartCoroutine ( ToggleBool (welcomeon, 5) );

After a delay of 5 seconds, this would turn on welcomeon and the coroutine should make it turn itself off 5 seconds later. However, this does not work, while specifically putting welcomeon in the coroutine works. Like this for example:

IEnumerator ToggleBoolz (float time)
		welcomeon = true;
		yield return new WaitForSeconds(time);
		welcomeon = false;

Is it just that coroutines do not work with bools? Or am I doing something wrong?

bool and floats are passed by value whereas objects are passed by reference. So the bool and float you modify in your coroutines aren’t the same variables that you passed in anymore, they’re copies.

You can almost make this work:

IEnumerator ToggleBool(ref bool test, float time)
	test = false;
	yield return new WaitForSeconds(time);
	test = true;

But C# doesn’t support ref or out variables from coroutines, so it looks like you can’t make a general use function for this.