2016-11-14 57 views
1

最近我開始開發一個Bukkit插件,我需要幫助在我的代碼中進行睡眠/等待。我有點新來java,所以如果你能解釋它,我會很感激。這裏是我的代碼:bukkit - 等待?

@EventHandler 
public void onTnt(PlayerInteractEntityEvent e) { 
    Player clicker = e.getPlayer(); 
    Player rightclick = (Player) e.getRightClicked(); 
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_PURPLE + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!"); 
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_RED + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!"); 
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!"); 
    /* Then wait 3 sec. I've tried Thread.Sleep, wait() and sleep(), no sucess*/ 

    if (!(rightclick.isSneaking())) { 
     rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "Bye bye."); 
     rightclick.setHealth(0); 

    } 

} 
+0

我不認爲等待或睡眠這裏是正確的想法,做一個新的bukkitrunnable,並安排其運行3秒鐘,以免睡眠插件的線程 – zack6849

回答

2

雖然通常你會使用Thread.sleep這樣的事情,這將凍結整個服務器,和事件不會在那個時間(處理,使得即使玩家停止偷偷摸摸他們的身邊,他們仍然會偷偷從服務器看到的東西)。

你需要做的是使用BukkitRunnable(或可替代常規RunnablegetServer().getScheduler().scheduleSyncDelayedTask):

@EventHandler 
public void onTnt(PlayerInteractEntityEvent e) { 
    Player clicker = e.getPlayer(); 
    // Needs to be final to reference it later 
    final Player rightclick = (Player) e.getRightClicked(); 
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_PURPLE + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!"); 
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.DARK_RED + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!"); 
    rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "AN INSTAKILLER HAS YOU AS A TARGET! SNEAK NOW!"); 


    BukkitRunnable task = new BukkitRunnable() { 
     @Override 
     public void run() { 
      if (!(rightclick.isSneaking())) { 
       rightclick.sendMessage(ChatColor.GRAY + "~" + ChatColor.GOLD + "Bye bye."); 
       rightclick.setHealth(0); 
      } 
     } 
    }; 
    // Run the task on this plugin in 3 seconds (60 ticks) 
    task.runTaskLater(this, 20 * 3); 
} 
0

我知道的事實,這是一個老問題,但我想補充這樣一來,那些將要尋找方法的用戶可能會發現這一點。

最簡單的說,這樣做是創建計劃任務:

Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { 
// The stuff which should be accomplished after the timer runs out goes here. 
// Example: 
player.sendMessage("The time has ran out!"); 
}, time); 

現在,讓我們通過了解這是怎麼回事的過程獲得。基本上,se創建了延遲任務(有兩種類型的計劃任務:延遲任務和重複任務)。 上述方法的第一個參數是this。這應該是你的主類(org.bukkit.plugin.java.JavaPlugin的子類)的一個實例。這意味着如果計劃的任務不在您的主類中,您需要將this替換爲它的一個實例。第二個參數是new Runnable() { ... },這裏我們實際上是在創建可運行的。無論在計時器耗盡時應該執行什麼,都應該進入花括號內。最後,最後一個參數:這是實際的延遲,在TICKS中測量。這意味着,如果你想等待x秒,你必須乘以x * 20,因爲蜱等於1/20秒,因此5秒將等於100個滴答聲。

如果你知道如何使用lambda表達式,可以更換匿名類:

Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this,() -> player.sendMessage("The time has ran out!"), time);