Stopwatch vs gameTime.

Just a quick question.
I have several classes in my project where something needs to happen after several milliseconds.

I know you can use the MonoGame gameTime to create a timer, but you can also do this with the C# stopwatch (System.Diagnostics) structure.
Does it matter what I use, or is one better than the other?

Thanks in advance

If you want the timer to be bound to actual game time you would have to pause the stopwatch when the game looses focus/is paused.

I would only use stopwatch for profiling and not any type of event behavior.

1 Like

Good inquiry ^_^y

I also want to know gameTime vs System.Environment.TickCount. I use TickCount to most of my timer and event firing really wanna know also the pros and cons.

My answer applies to that property as well.

How would you handle scenarios such as pause if you’re basing the timer on time elapsed since boot up?

1 Like

Thanks for the answer @Olivierko!

I’d be interested to hear what others do. It never crossed my mind to use StopWatch for the gametime.

This might be a good read for you: http://rbwhitaker.wikidot.com/gametime. GameTime has properties synced with your game. StopWatch wouldn’t unless you create that logic. For example, GameTime has ElapsedGameTime which will tell how much time from the last update() call. GameTime also has TotalGameTime which is a stopwatch essentially from the start of your game.

I use GameTime. When I need a timer, you just have to save the gameTime.TotalGameTime.TotalMilliseconds and check against it. I just use the logic below.

    public double Timer = 0.0;
    public double DelayTime = 0.0;

    public void Update(GameTime gt)
    {
        if (this.Timer <= gt.TotalGameTime.TotalMilliseconds)
        {
            Timer = gt.TotalGameTime.TotalMilliseconds + DelayTime;
            // Do your stuff
        }
    }

I got tired of creating that so I created a Delay utility class in my game to make easier. It looks something like this (this might not work because I had to make a few changes to paste it here and didn’t test before pasting here, you’ll get the idea though)

class Delay
{
    public double Timer = 0.0;
    public double DelayTime = 0.0;
    
    public Delay(double DelayTime)
    {
        this.DelayTime = DelayTime;
    }

    public void Wait(GameTime gt, Action Action)
    {
        if (this.Timer <= gt.TotalGameTime.TotalMilliseconds)
        {
            Timer = gt.TotalGameTime.TotalMilliseconds + DelayTime;
            Action.Invoke();
        }
    }
}

Then I call it like

Delay Timer = new Delay(50.0);
public override void Update(GameTime gt)
{
     Timer.Wait(gt, () =>
     {
          // do my timer based code...
     });
}

Side note: I moved my GameTime into a static class so I didn’t have to pass it via parameters through my update(). So my delay class doesn’t get passed GameTime, it just calls the static class for it.

1 Like