- Home /
Yield not working in C#
I'm trying to build FPS counter that will change only once per second in C#.
I have this in class definition:
float FPS;
This in void OnGUI()
:
GUI.Label(new Rect(0, 30, 600, 30), string.Format("FPS: {0}", this.FPS));
StartCoroutine(ShowFPS());
And this function in class:
IEnumerator ShowFPS()
{
FPS = 1 / Time.smoothDeltaTime;
yield return new WaitForSeconds(1);
}
The FPS counter still changes every frame although the yield return new WaitForSeconds(1);
If I put the StartCoroutine(ShowFPS());
in Update
the same thing happens and if I put it in Start
it just says FPS: Infinity
.
How do I make the yield return new WaitForSeconds(1);
wait 1 second?
Answer by Mike 3 · Mar 30, 2011 at 10:55 AM
Currently it is waiting a second - the issue is that nothing happens after that one second, and every frame you're calling another coroutine which does the same thing - changes the fps, then waits a second before doing nothing
What you should do instead is something like:
void Start() { InvokeRepeating("UpdateFPS", 1, 1); }
void UpdateFPS() { FPS = 1 / Time.smoothDeltaTime; }
Which doesn't use coroutines, but easier to understand code
Sure, but it's not going to be noticeable - the dynamic cost will only be done once, after that it's a direct function call from c++
Answer by Dani · Mar 30, 2011 at 10:57 AM
Found the problem myself, adding while(true)
inside the coroutine and moving the StartCoroutine
to Start
did the trick.
Your answer
Follow this Question
Related Questions
Wait to Reload 2 Answers
Frame counter not registering - Component missing? 1 Answer
[ Coroutine: Move Next ] CPU usage 0 Answers
Yield WaitForSeconds only works sometimes?! 1 Answer
iOS Polygon button not working with yield WaitForSeconds 0 Answers