Question

Apologies for terrible use of words but I'm not into the lingo yet.

I've been creating a spell book for a simple bukkit plugin which opens into an inventory on the right click of a certain custom item that is crafted. Here is the code

@EventHandler
public void onBookInteract(PlayerInteractEvent e){
    if(e.getAction() == Action.RIGHT_CLICK_AIR){
        if(e.getItem() == SpellBook){
            openGUI(e.getPlayer());

When I try to do this ingame nothing happens. I've removed if(e.getItem() == SpellBook){ and it works as well as if I change the statement to:

if(e.getMaterial() == Material.BLAZE_POWDER){

It works as well. Probably a simple error but I only started coding a couple of days ago. Thanks for any and all helpful feedback ^_^

Was it helpful?

Solution

There are a couple things that could be wrong.

1) Make sure that the class that this is in implements Listener, and that in your Main class, (the one that extends JavaPlugin) in the onEnable() method, you have:

this.getServer().getPluginManager().registerEvents(new <class that implements Listener>(), this);

so if the class that your code with @EventHandler is in is called Handler, then you would use:

this.getServer().getPluginManager().registerEvents(new Handler(), this);

2) Try using .equals() instead of ==:

if(e.getAction().equals(Action.RIGHT_CLICK_AIR)){
    if(e.getItem().equals(SpellBook)){

3) Make sure that SpellBook is actually an ItemStack. If it is, then you may want to try doing this if it has no ItemMeta (display name, lore, etc.)

if(e.getItem().getType().equals(SpellBook.getType())){

Otherwise, if it does have ItemMeta, you could use this:

if(e.getItem().getType().equals(SpellBook.getType()) && e.getItem().hasItemMeta()){
  if(e.getItem().getItemMeta().getDisplayName().equals(SpellBook.getItemMeta().getDisplayName(){
    if(e.getItem().getItemMeta().getLore().equals(SpellBook.getItemMeta().getLore(){  

So, your final code should probably look something like this:

@EventHandler
public void onBookInteract(PlayerInteractEvent e){
  if(e.getAction().equals(Action.RIGHT_CLICK_AIR)){
    if(e.getItem().getType().equals(SpellBook.getType()) && e.getItem().hasItemMeta()){
      if(e.getItem().getItemMeta().getDisplayName().equals(SpellBook.getItemMeta().getDisplayName()){
        if(e.getItem().getItemMeta().getLore().equals(SpellBook.getItemMeta().getLore()){
          openGUI(e.getPlayer());
        }
      }
    }  
  }
}

OTHER TIPS

If SpellBook is a type (i.e. a Java class) then that's your problem, e.getItem() returns an instance of a class. Again, if SpellBook is a type (I can't tell with the brief code you gave), then try using e.getItem() instanceof SpellBook instead. Sorry if I'm way off.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top