Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wonder if there is a simple way to use some kind om interval timing in XNA? For example call a method every 10 seconds?

I'm also wondering if there is a way to hide and unhide a sprite when it's on the screen?


share|improve this question
up vote 4 down vote accepted

Question 1:

To expand on Jason's answer, I typically handle it by creating a couple variables:

float timer = 10;         //Initialize a 10 second timer
const float TIMER = 10;

Then in the Update() method, you can then do something like this:

public void Update(GameTime gameTime)
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    timer -= elapsed;
    if (timer < 0)
        //Timer expired, execute action
        timer = TIMER;   //Reset Timer

Question 2:

Create a variable:

bool drawSprite = true;

Set this variable in your code, depending on where you want to switch it on or off. You could set it inside of your timer action, so it would flip on/off every 10 seconds.

if (timer < 0)
    drawSprite = !drawSprite;
    timer = TIMER;   //Reset Timer

Then in your Draw() function:

public void Draw()
    if (drawSprite)
share|improve this answer
Nice! This appears to be a good solution! – 3D-kreativ Jul 12 '12 at 21:53
ElapsedGameTime is the time elapsed since the last update. Hopefully, for the sake of your game's responsiveness, the TotalSeconds will always be zero for this, so the timer variable in this example will never reach zero. You may need to use ElapsedGameTime.TotalMilliseconds/1000 instead. Or use the whole TimeSpan struct as Jason implicitly suggests. – indeed005 Jul 13 '12 at 1:24
Hmm, thanks for the advice, but none of the code example works! Nothing happens after 10 sec! – 3D-kreativ Jul 13 '12 at 8:49
It only works with this code: if (timer < 1) – 3D-kreativ Jul 13 '12 at 8:58
Yes, the original code was checking the float against zero, which is very wrong. Modified it to check if < 0 – Jon Jul 13 '12 at 10:58

You could have a timer variable, and add gameTime.ElapsedGameTime to it on every update().

As for your second question: in your draw() function, use an if statement for drawing sprites.

share|improve this answer
Thanks! But it had been easier to understand with some code example – 3D-kreativ Jul 12 '12 at 21:32

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.