WaitForSeconds and UI Text Elements
Hi there! :) Just a question. I'm trying to basically get a message printed out on the screen and after about 5 seconds it goes away.
Tried this code and many variations of it and I cant get it to work. In fact it looks like the text never shows (though it does, but only for a frame, I guess)...
I'm sure I'm doing something wrong. Just can't pinpoint what...
Cheers!
void ShowMessage(string message)
{
gameMessage.text = message;
gameMessageShadow.text = message;
StartCoroutine(WaitATick());
gameMessage.text = "";
gameMessageShadow.text = "";
}
IEnumerator WaitATick()
{
yield return new WaitForSeconds(5);
}
Answer by Sgt_Spike · Jun 15, 2018 at 01:24 PM
@savrasbane Yes, I can see where you have gone wrong. I assume what you think is happening is that when the coroutine is called from 'StartCoroutine(WaitATick())', the other lines of code below it will not be executed until the 'WaitATick()' coroutine is finished. What I'm trying to say is that all five of your lines of code in ShowMessage() are going to be executed straight away, so at the moment, your coroutine is doing nothing.
All you need to do here is move the last two lines of code, these being 'gameMessage.text = "";' and 'gameMessageShadow.text = "";' into your coroutine under the 'yield return new WaitForSeconds(5);'.
Hopefully you understand!