- Home /
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 :)
Answer by whydoidoit · Apr 08, 2013 at 08:27 AM
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());
$$anonymous$$g.
IEnumerator YourFunction()
{
yield return new WaitForSeconds(5);
message = "";
}
Answer by Nidre · Apr 08, 2013 at 08:29 AM
Havent tested the code but the logic should work :) Hope this helps :)
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.
Your answer
Follow this Question
Related Questions
WaitUntil Combined With sqrMagnitude is not working? 1 Answer
Wierd issue with Coroutines? 2 Answers
yield new wait for seconds: what does "new" do? 1 Answer
help with yield function 2 Answers
C# Coroutine help 1 Answer