Global Frame Counter

Hello Everyone,

After finally having debugged quite some parts of my code, I was curious on how I could write a global method that can be called on in any script which counts frames. So that if the method is used in script A and in script B, both of them will have the same frame count. After 20 frames, the method starts counting from zero again. Previously I was only able to count up, however I am struggling with the reset after 20 frames.

public static class WaitFor
    {
        public static IEnumerator Frames(int frameCount)
        {
            while (frameCount > 0)
            {
                frameCount--;
                yield return null;
            }
        }
    }

If you want to do something every frame, you should use an Update function. (A coroutine could work, but doesn’t really have any advantages. Note that coroutines need to be running on an active GameObject in order to work, so your attempt to create one in a static class isn’t likely to work out.)

To reset a variable, just set it equal to zero (or whatever the “reset” value is). Like frameCount = 0. No need to use a loop.

But you might find it’s more useful to have the counter keep going up forever, and have a helper function that returns (frameCount % 20) to get a version that “wraps around” every 20 frames. This way you can still use the true, non-resetting frameCount if you ever want it for some reason.

2 Likes

Ok, thats good as Id like to avoid using a coroutine. How can I count frames first of all ? with IEnumerator ? I am exploring different methods atm. So any suggestion would be appreciated.

There is a frame counter on the time class

Edit: if you want to count down frames (makes no sense being framedependet though) you can use the WaitUntil yield instruction. Capture the frame count when start wait and then check if number of frames have passed.

Again WairForSexonds is orobalby what you want todo