我制作了一个插件,用来跟踪您在Minecraft中开采的钻石数量并将其保存到config.yml文件中。但是我的代码似乎不起作用,我不知道为什么吗?
我已经在setConfig参数中尝试过+1,但是现在我切换到了+1,它似乎仍然无法正常工作。我的config.yml文件中也预定义了钻石。
package com.raidoxe.BlockPlugin;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
@Override
public void onEnable() {
getLogger().info("Sartu has been enabled :)");
PluginManager pm = getServer().getPluginManager();
SartuListener listener = new SartuListener(this);
pm.registerEvents(listener, this);
this.getConfig().options().copyDefaults(true);
this.saveConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = (Player) sender;
if (sender instanceof Player) {
String lowerCmd = cmd.getName().toLowerCase();
switch (lowerCmd) {
case "mydiamonds":
int a = this.getConfig().getInt("diamonds."+player.getUniqueId());
player.sendMessage(ChatColor.DARK_PURPLE+"You have mined "+ChatColor.RED+a+ChatColor.AQUA+" Diamonds");
return true;
}
}
return true;
}
------------Listener File-----------
package com.raidoxe.BlockPlugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
public class SartuListener implements Listener {
private Plugin plugin = Main.getPlugin(Main.class);
public SartuListener(Main plugin) {
}
@EventHandler
public void blockBreak(BlockBreakEvent event) {
Player player = (Player) event.getPlayer();
Block block = event.getBlock();
Material blockMaterial = block.getType();
if(blockMaterial.equals(Material.DIAMOND_ORE)) {
Bukkit.broadcastMessage(ChatColor.WHITE+player.getDisplayName()+" found a "+ ChatColor.AQUA + ChatColor.BOLD+"Diamond!!!");
int a = plugin.getConfig().getInt("diamonds."+player.getUniqueId());
plugin.getConfig().set("diamonds."+player.getUniqueId(), a++);
plugin.saveConfig();
}
}
当玩家执行命令/ mymondmonds时,应该打印出“您已开采(a)颗钻石”。但是无论您开采了多少颗钻石,它始终会输出零。
答案 0 :(得分:1)
您的代码看起来很正常,除了一个小错误。您说您已经在setConfig中尝试过+1,所以如果此解决方案不适合您,则可能是版本问题
如果配置getInt()
返回0,则可能意味着两件事:
测试后,配置中确实存在该值(由于saveConfig()
,但该值设置为0。因此,我将其引向设置方法。
问题是增加的部分。您在方法内部执行++,这将使我们想要在方法之前之后的数量增加,切换到++ a。 See this post。
if(blockMaterial.equals(Material.DIAMOND_ORE)) {
Bukkit.broadcastMessage(ChatColor.WHITE+player.getDisplayName()+" found a "+ ChatColor.AQUA + ChatColor.BOLD+"Diamond!!!");
int a = plugin.getConfig().getInt("diamonds."+player.getUniqueId());
plugin.getConfig().set("diamonds."+player.getUniqueId(), ++a);
plugin.saveConfig();
}