Question

so I've been working on a new minigame that is pretty hectic with the timers. It's basically a fast-paced parkour game, but the issue is that while my timers work, they affect all online players at once. How would I limit a timer to a player? I read a bit on it, and I saw that a lot of solutions was storing the player name and task ID in a HashMap, but I don't know where to go from that point. A little guidance will be appreciated!

Was it helpful?

Solution

You could simply create a separate timer for each player, and then store the ID in a HashMap:

public Map<String, Integer> taskID = new HashMap<String, Integer>();

//call this to schedule the task
public void scheduleRepeatingTask(final Player p, long ticks){
  final int tid = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable(){
    public void run(){
      //do you want here
    }
  },ticks, ticks); //schedule task with the ticks specified in the arguments

  taskID.put(p.getName(), tid); //put the player in a hashmap
}

//call this to end the task
public void endTask(Player p){
  if(taskID.containsKey(p.getName()){
    int tid = taskID.get(p.getName()); //get the ID from the hashmap
    plugin.getServer().getScheduler().cancelTask(tid); //cancel the task
    taskID.remove(p.getName()); //remove the player from the hashmap
  }
}

OTHER TIPS

Do not make a separate task for each player, as said above (i don't have enough reputation to comment) make a task decrementing a counter in a HashMap, and when the counter reaches zero remove players UUID from HashMap

Coding separate task for each player is pointless, it increases CPU load as it has to handle lots of Threads instead of one

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top