我正在尝试创建一个欢迎最近加入的播放器的命令,但是加入侦听器不会替换lastPlayer变量,因此当您键入/ welba时,它只会显示null。
package me.spoonle.welba.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import me.spoonle.welba.Main;
import me.spoonle.welba.Utils.Utils;
public class WelbaCommand implements CommandExecutor {
private Main plugin;
public WelbaCommand(Main plugin) {
this.plugin = plugin;
plugin.getCommand("welba").setExecutor(this);
}
public static String lastPlayer = null;
@EventHandler
public void onJoin(PlayerJoinEvent e) {
lastPlayer = e.getPlayer().getName();
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(Utils.chat("&cYou don't have access to this command! Only players can use this command!"));
return true;
}
Player p = (Player) sender;
if (p.hasPermission("welba.use")) {
p.chat("Welcome Back, " + lastPlayer);
} else {
p.sendMessage("&cYou don't have use to this command!");
}
return false;
}
}
有我的插件代码。我需要更改收听者的位置吗?我尝试为其创建一个单独的类,但是当我在Main类中调用lastPlayer时,它不会选择该变量。
答案 0 :(得分:2)
您需要实现Listener
接口并将该类注册到您的主类中。
在Listener
中注册Main.java
类:
public class Main extends JavaPlugin {
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(new MyListener(), this);
}
}
并在MyListener.java
中实现监听器:
public class MyListener implements org.bukkit.event.Listener {
@EventHandler
public void onJoin(PlayerJoinEvent event) {
// implement your handling ...
event.getPlayer().sendMessage("§cIt works!");
}
}
有关更多信息,请参见this。