yield wait error iterator block

I’m trying to have a timer after a message pops up in a label so after 3 seconds it becomes a blank label. But when I use the code below i get the error:

Assets/GameGrass/SHOWMESSAGE.cs(8,6): error CS1624: The body of SHOWMESSAGE.Update()' cannot be an iterator block because void’ is not an iterator interface type

any help? :S

public class SHOWMESSAGE : MonoBehaviour {

	private string message = "";
 
void Update()
{
 if (Input.GetKeyDown("h")) // You must use 'Input' only at the 'Update' functions
 {
    if(variablesResources.GetWood() >= 3)
    {
      message = "YOU BUILT A HOUSE";
      variablesResources.SetWood(-3);
		yield return new WaitForSeconds(5);
		message = "";
      
    }
    else
    {
         message = "YOU DONT HAVE ENOUGH WOOD";
    }
  }
}
void OnGUI() // Is not static and you should not be making it so
{
    GUI.Label(new Rect(50, 50, 300, 20), message);
}

@Nidre - it's an answer - make it an answer not a comment :)

my bad :) Wrong button :)

2 Answers

2

An Update function cannot be a coroutine (and therefore cannot yield).

It can however start one - but in this case you just want to use Invoke:

   if(variablesResources.GetWood() >= 3)
{
  message = "YOU BUILT A HOUSE";
  variablesResources.SetWood(-3);
   Invoke("HideMessage", 5);


}

...

void HideMessage() 
{
   message = "";
}

You start a coroutine from Update using StartCoroutine(YourFunction()); E.g. IEnumerator YourFunction() { yield return new WaitForSeconds(5); message = ""; }

this worked perfectly! :D Thank you very much.

Havent tested the code but the logic should work :slight_smile: Hope this helps :slight_smile:

void Update()
{
	if (Input.GetKeyDown("h")) // You must use 'Input' only at the 'Update' functions
	{
		StartCoroutine("WaitThreeSeconds");
	}
}

IEnumarator WaitThreeSeconds()
{
	if(variablesResources.GetWood() >= 3)
	{
		message = "YOU BUILT A HOUSE";
		variablesResources.SetWood(-3);
		yield return new WaitForSeconds(5);
		message = "";		 
	}
	else
	{
		message = "YOU DONT HAVE ENOUGH WOOD";
	}
}

You might also need to control if there is already an Coroutine waiting for 3 seconds to avoid complications.You can call StopCoroutine("WaitThreeSeconds"); before calling StartCoroutine("WaitThreeSeconds"); to make sure that only one WaitThreeSeconds is active.Or you can use a boolean flag an check before starting coroutine if any WaitThreeSeconds routine is already active.