我的世界Bedwars插件Bukkit自定义死亡系统倒计时异常问题求助
问题修复方案
核心问题根因
- 原代码中
count定义在定时任务的lambda内部,每次任务执行都会重新初始化值为5,永远无法减到0 - 改用类公共变量会导致所有玩家的死亡倒计时共享同一个计数,多次死亡后变量状态混乱,出现提前重生问题
修复方法
在每次触发死亡事件时,为当前玩家的独立倒计时创建专属的计数器,利用Java闭包特性捕获可变原子类计数器即可,无需定义全局变量:
import java.util.concurrent.atomic.AtomicInteger; import org.bukkit.scheduler.BukkitTask; // 类内其他代码省略 @EventHandler public void onPlayerDeath(PlayerDeathEvent e) { e.getEntity().spigot().respawn(); String[] pos = Main.death_coords.split("\\*"); World w = e.getEntity().getWorld(); Location loc = new Location(w, Double.parseDouble(pos[0]), Double.parseDouble(pos[1]), Double.parseDouble(pos[2])); e.getEntity().teleport(loc); e.getEntity().setGameMode(GameMode.SPECTATOR); // 为本次死亡创建独立的倒计时计数器,仅当前任务可访问 AtomicInteger count = new AtomicInteger(5); BukkitTask task = Bukkit.getServer().getScheduler().runTaskTimer(Main.plugin, () -> { int current = count.getAndDecrement(); if(current == 0) { task.cancel(); sendtitle("SusyBaka", e.getEntity()); e.getEntity().setGameMode(GameMode.SURVIVAL); } else { sendtitle(Integer.toString(current), e.getEntity()); } }, 20, 20); }
修复说明
- 每次死亡事件触发时都会创建新的
AtomicInteger实例,不同玩家、不同次死亡的倒计时完全隔离,不会互相干扰 - 计数器的状态保存在lambda外部的闭包中,不会随每次任务执行重置,可正常完成5→0的倒计时
task变量改为方法内局部变量,避免全局task变量被后续死亡事件覆盖导致旧任务无法正常取消的问题
内容的提问来源于stack exchange,提问作者Sysy
相关产品推荐
相关产品推荐

