Reputation: 635
Hi I have been trying to make a simple 10 second countdown timer for my libgdx game for hours now but I keep running into problems. I am now running the countdown timer in a separate class which implements runnable. This class works perfectly and it counts down the time as planned, I have ran a system.out.println within this thread to verify it working. The problem is printing/drawing this timer variable in my main game screen.
If I try to print this variable from my game screen I get the starting variable of it i.e. ten rather than the constantly updating one(counting down from ten). I have even used a getter method with still no luck. Any ideas how to achieve this? Thanks
I am assuming this is because the Thread is running parallel to the main game?
public class timekeep implements Runnable {
public Boolean TimerRunning=true;
private int Timer = 10; //need to print this from my main game screen as it changes
public void run() {
while(TimerRunning == true) {
System.out.println("Time left "+ Timer);//works perfectly prints countdown
//run code
//subtracts 1 from Timer every second
}
}
public int gettime(){
return Timer;//returns timer
}
}
....
//accessing Timer variable from main game
System.out.println(Timekeep.gettime());//prints 10 all the time in the main screen
Upvotes: 0
Views: 458
Reputation: 16261
Well your code executes two new timekeep()
expressions and so two objects are created. You need to recode so that only one timekeep
object is created. E.g.
timekeep theTimeKeeper = new timekeep() ;
Thread t1 = new Thread(theTimeKeeper));
t1.start() ;
...
System.out.println(theTimeKeeper.gettime());
Upvotes: 1