0

I am creating a plugin, with Bukkit in Minecraft : 1.19.4 and I need to see if there is a specific Music Disc in a JukeBox when the player right clicks on the block but I can't find a way to do that.

So I tried:

public class TestCD implements Listener {

    @EventHandler
    public void onInteract(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        Action action = event.getAction();
        ItemStack it = event.getItem();
        Block block = event.getClickedBlock();
        BlockData blockD = block.getBlockData();


        if (it != null && action == Action.LEFT_CLICK_BLOCK && block.getType().equals(Material.JUKEBOX) && blockD.getMaterial().isRecord() = true) {
            player.sendMessage("Hello World");
        }
    }

Then I tried several other things but I don't remember them.

pppery
  • 3,731
  • 22
  • 33
  • 46
Daweii
  • 3
  • 1

1 Answers1

0

To get the record, if any, playing inside of a JukeBox, you can use the JukeBox block state method getRecord() like so:

    ...
    if(!(block.getState() instanceof Jukebox))
        return;
    Jukebox jukebox = (Jukebox) block.getState();
    ItemStack record = jukebox.getRecord();
    ...

You must ensure that your block variable isn't null before attempting to cast. If there is no disc in the jukebox, the resulting ItemStack will be of type Material.AIR.

Edit: Here's a complete example:

@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent e) {
    // Ensure we want to do something with this event
    if(e.getAction() != Action.LEFT_CLICK_BLOCK
            || e.getClickedBlock() == null
            || e.getClickedBlock().getType() != Material.JUKEBOX
            || !(e.getClickedBlock().getState() instanceof Jukebox)
    ) {
        return;
    }
    Player player = e.getPlayer();
    // Cast the clicked block's state to JukeBox
    Jukebox jukebox = (Jukebox) e.getClickedBlock().getState();
    // Get the record in the JukeBox
    ItemStack record = jukebox.getRecord();
    // If the record's material type is AIR, there is nothing playing
    if(record.getType() == Material.AIR){
        player.sendMessage("There is nothing playing in this JukeBox.");
        return;
    }
    // Do whatever with the record; below is just an example...
    StringBuilder message = new StringBuilder("This JukeBox");
    // Check if it's currently playing
    if(jukebox.isPlaying()){
        message.append(" is currently ");
    } else {
        // If it's not playing, that means a record is in the JukeBox, but it's not playing
        message.append(" was previously ");
    }
    player.sendMessage(message + "playing " + record.getType().name());
}
Lucan
  • 2,907
  • 2
  • 16
  • 30