I have a maze game and I’m trying to create two Timers at a time.
1st (Exits the game after 300 secs)
t1.Interval = 30000;
t1.Enabled = true;
t1.Elapsed += new ElapsedEventHandler(hiddenTimer);
public static void hiddenTimer(object source, ElapsedEventArgs e)
{
Console.Clear();
Environment.Exit(1);
}
2nd (Displays the time remaining every 1 sec (like a real timer))
t2.Interval = 1000;
t2.Enabled = true;
t2.Elapsed += new ElapsedEventHandler(showTimer);
public static void showTimer(object source, ElapsedEventArgs e)
{
Console.Write(timeLeft);
}
I would want to pass declare timeLeft globally but it says that “An object reference is required for the non-static field, method, or property…”
How would I declare it properly?
First of all, you should declare your timeLeft as a static if you want it to behave like a global variable.
Secondly I’d use one timer and keep track of the time separately for each event:
In your timer, which should be set to something to give more accuracy like 1/10 of a second, do this:
Your timings will be more accurate this way.