Bukkit (spigot api) listener not responding?

可紊 提交于 2019-12-25 03:49:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!