提问者:小点点

Minecraft Bukkit和Spigot在点唱机中获取项目


我正在创建一个插件,与Bukkit在Minecraft: 1.19.4和我需要看看是否有一个特定的音乐光盘在点唱机当玩家右键点击块,但我找不到一个方法来做到这一点。

所以我尝试了:

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");
        }
    }

然后我尝试了其他几件事,但我不记得了。


共1个答案

匿名用户

要获取在JukeBox中播放的记录(如果有),您可以使用JukeBox块状态方法getRecords(),如下所示:

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

在尝试强制转换之前,您必须确保您的block变量不为空。如果点唱机中没有光盘,则生成的ItemStack将是Material. AIR类型。

编辑:这是一个完整的例子:

@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());
}