问题
I have been making a bukkit plugin, which shows up in the plugins list but when I do what I want the code to do nothing happens.
public class MyClass extends JavaPlugin implements Listener {
@EventHandler
public void onInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (player.isSneaking()) {
player.sendMessage("Fire!");
Arrow arrow = player.launchProjectile(Arrow.class);
arrow.setShooter(player);
arrow.setGravity(false);
arrow.setSilent(true);
arrow.setBounce(false);
Block attach = arrow.getAttachedBlock();
Location attachlocation = attach.getLocation();
attachlocation.getWorld().createExplosion(attachlocation, 3);
arrow.setVelocity((player.getEyeLocation().getDirection().multiply(1000)));
}
}
}
回答1:
I can't see you registering your listener. Bukkit needs to know what objects are listeners (you're not doing this) and it needs to know what methods to execute (with the @EventHandler
annotation)
You can register the listener with PluginManager's registerEvents(Listener listener, Plugin plugin) method. A smart idea is to do this inside your onEnable method, to ensure your listener is registered as soon as your plugin starts.
public class MyClass extends JavaPlugin implements Listener {
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
}
// rest of your code
}
回答2:
Just a quick tip,
If you want to register a listener for a different class then the code in #onEnable() would be:
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this); //You have to
register the main class as a listener too.
this.getServer().getPluginManager().registerEvents(new EventClass(), this);
}
Thanks!
回答3:
The listener class code you are trying to call would be helpful to try and debug this scenario. You must make sure the following is true:
1) Class implements Listener
2) You register the class using:
Bukkit.getServer().getPluginManager().registerEvents(new [class] /* class of listener. this if it's your main class */, this/* your main class */);
3) You remembered @EventHandler before every event.
If you are learning bukkit programming it may be worth checking out this video: https://youtu.be/Rinjdx6c6r8 and this series:
https://www.youtube.com/watch?v=bVySbfryiMM&list=PLAF3anQEEkzREsHA8yZzVhc3_GHcPnqxR
来源:https://stackoverflow.com/questions/52866183/bukkit-spigot-api-listener-not-responding