Yield WaitForSeconds doesn't work!
I've got this code here and want it to wait 3 sec, before the check boolean gets reversed, but I'm unable to make this happen, since I've obviously put a mistake in my code which I don't find.
My aim is, to make the text fade out and then in again, endlessly.
using UnityEngine;
using System.Collections;
public class BlinkingText : MonoBehaviour {
float duration = 3;
public GUIText guiText;
public bool check = false;
void Update () {
if (check == false) {
Color myColor = guiText.color;
float ratio = Time.time / duration;
myColor.a = Mathf.Lerp (1, 0, ratio);
guiText.color = myColor;
Pause ();
check = !check;
}
else if (check == true) {
Color myColor = guiText.color;
float ratio = Time.time / duration;
myColor.a = Mathf.Lerp (0, 1, ratio);
guiText.color = myColor;
check = !check;
}
}
IEnumerator Pause() {
yield return new WaitForSeconds(3);
}
}
Please help!
Update cannot be yielded. You could move all your code into something other than Update, and then use InvokeRepeating to achieve the desired effect.
Answer by Mikilo · Sep 01, 2015 at 03:54 PM
Hello.
Calling Pause() in Update wont make it run correctly.
Since it is a coroutine, you need to call it through StartCoroutine().
My advice would be to put all your code in a coroutine and call it in Start().
Like that:
float duration = 3;
public GUIText guiText;
public bool check = false;
void Start()
{
StartCoroutine(this.Fade());
}
IEnumerator Fade()
{
float timeLeft = duration;
float timePassed = 0F;
while (true)
{
myColor.a = Mathf.PingPong(timePassed, 1F);
guiText.color = myColor;
timeLeft -= Time.deltaTime;
timePassed += Time.deltaTime;
if (timeLeft < 0F)
{
timeLeft = duration;
yield return new WaitForSeconds(duration);
}
else
yield return null;
}
}
thank you very much, it works fine to 99%! :D
the 1% problem is that it doesn't fade anymore, the text gets just appears and disappears...
any ideas?
I just had to add
Color myColor = guiText.color;
in line 16, but hell yeah that's it then! :D
thank you so much!!
Your answer
Follow this Question
Related Questions
Coroutine: delay transform rotation but start transform movement immediately 2 Answers
Unity WaitForSeconds Not Working Inside Update or a Loop 2 Answers
yeild return new WaitForSeconds doesn't work 1 Answer
Question to WaitForEndOfFrame 2 Answers
How to add multiple yield return new wait for seconds inside an IEnumerator? 1 Answer