0

I need a way to spawn objects in a level at set time. I know I can do this with If statements by checking the time variables, but this idea is stupid because it checks ewery update if its the right time and this will make my game slower. Is there another way? I am programming in Java. And sorry for bad English.

Pimgd
  • 5,983
  • 1
  • 30
  • 45
Simas
  • 31
  • 1
  • 6

1 Answers1

2

You'll want to use Java's Timer class, http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html

Here's a simple example:

public class Reminder 
{
    Timer timer;

    public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }

    class RemindTask extends TimerTask {
        public void run() {
            System.out.println("Time's up!");
            timer.cancel(); //Terminate the timer thread
        }
    }

    public static void main(String args[]) {
        new Reminder(5);
        System.out.println("Task scheduled.");
    }
}

In your instance, you'll want to replace the timer schedule method call from the seconds argument to a Date variable. You'll be using this constructor:

schedule(TimerTask task, Date time) Schedules the specified task for execution at the specified time.

Hope this helps you!

Greg Hilston
  • 2,397
  • 2
  • 24
  • 35