Bukkit:Player.teleport()抛出NullPointerException

时间:2015-04-07 15:58:30

标签: java nullpointerexception bukkit

我正在制作setspawnspawn命令,但“/spawn”不起作用。我使用的是Bukkit 1.8.3。谁知道为什么?这是完整的代码:

相关代码

/ setspawn

if (cmd.getName().equalsIgnoreCase("setspawn")) {
    if (!sender.hasPermission("setspawn")) {
        sender.sendMessage(ChatColor.RED + "Access denied.");
        return true;
    }

    if (!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "CONSOLE Cannot set spawn!");
        return true;
    }

    if (sender instanceof Player) {
        Player player = (Player) sender;

        getConfig().set("spawn.world", player.getLocation().getWorld());
        getConfig().set("spawn.x", player.getLocation().getX());
        getConfig().set("spawn.y", player.getLocation().getY());
        getConfig().set("spawn.z", player.getLocation().getZ());
        saveConfig();
        player.sendMessage(ChatColor.GREEN + "Spawn has been set!");

        return true;
    }
}

/卵

if (cmd.getName().equalsIgnoreCase("spawn")) {
    if (!sender.hasPermission("spawn")) {
        sender.sendMessage(ChatColor.RED + "Access denied.");
        return true;
    }

    if (!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "CONSOLE Cannot teleport to spawn!");
        return true;
    }

    if (getConfig().getConfigurationSection("spawn") == null) {
        Player player = (Player) sender;
        player.sendMessage(ChatColor.RED + "Spawn is not set!");
        return true;
    }

    if (sender instanceof Player) {
        Player player = (Player) sender;
        World w = Bukkit.getServer().getWorld(getConfig().getString("spawn.world"));
        double x = getConfig().getDouble("spawn.x");
        double y = getConfig().getDouble("spawn.y");
        double z = getConfig().getDouble("spawn.z");

        player.teleport(new Location(w, x, y, z));

        return true;
    }
}

完整代码

package me.herobrine112211.ulticmdpack;

import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

public class System extends JavaPlugin implements Listener {
    public static Economy econ = null;

    public void onEnable() {
        if (!setupEconomy()) {
            getLogger().severe(String.format("[%s] - Disabled because vault was not found!", getDescription().getName()));
            getServer().getPluginManager().disablePlugin(this);
            return;
        }

        getConfig().options().copyDefaults(true);
        saveConfig();
        Bukkit.getServer().getPluginManager().registerEvents(this, this);
        Bukkit.getServer().getLogger().info("Ultimate Command Pack Plugin has been actived!");
    }

    private boolean setupEconomy() {
        if (getServer().getPluginManager().getPlugin("Vault") == null) {
            return false;
        }

        RegisteredServiceProvider < Economy > rsp = getServer().getServicesManager().getRegistration(Economy.class);

        if (rsp == null) {
            return false;
        }

        econ = rsp.getProvider();
        return econ != null;
    }

    public void onDisable() {
        Bukkit.getServer().getLogger().info("Ultimate Command Pack Plugin has been disabled! This will give big problems to server.");
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent joinevent) {
        Player getplayer = joinevent.getPlayer();

        getplayer.sendMessage(ChatColor.AQUA + "Hey " + getplayer.getName() + "! Welcome to the Ultimate Prison server!");

        if (getplayer.getName().equals("Herobrine112211")) {
            Bukkit.getServer().broadcastMessage(ChatColor.WHITE + "[" + ChatColor.GOLD + "BROADCAST" + ChatColor.WHITE + "] " + ChatColor.GOLD + "Server Creator Herobrine112211 has joined the game!!!!!!!!!!");
        }
    }

    @SuppressWarnings("deprecation")
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        if (cmd.getName().equalsIgnoreCase("contactowner")) {
            if (!sender.hasPermission("contactowner")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (!(sender instanceof Player)) {
                sender.sendMessage(ChatColor.RED + "Console will never need owner support.");
                return true;
            }

            if (sender instanceof Player) {
                Player player = (Player) sender;
                player.sendMessage(ChatColor.GOLD + "Owner: Herobrine112211. Live chat skype: gangsteris33.");
                return true;
            }
        }

        if (cmd.getName().equalsIgnoreCase("reloadconfig")) {
            if (!sender.hasPermission("config.reload")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            reloadConfig();
            sender.sendMessage(ChatColor.RED + "Server config reloaded successfully.");
            return true;
        }

        if (cmd.getName().equalsIgnoreCase("saveconfig")) {
            if (!sender.hasPermission("config.save")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            reloadConfig();
            sender.sendMessage(ChatColor.RED + "Server config saved successfully.");
            return true;
        }

        if (cmd.getName().equalsIgnoreCase("fakeop")) {
            if (!sender.hasPermission("fake.op")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (args.length == 0) {
                sender.sendMessage(ChatColor.RED + "Please specify a player!");
                return true;
            }

            Player target = Bukkit.getServer().getPlayer(args[0]);

            if (target == null) {
                sender.sendMessage(ChatColor.RED + "Player must be online!");
                return true;
            }

            target.sendMessage(ChatColor.YELLOW + "You are now op!");
        }

        if (cmd.getName().equalsIgnoreCase("fakejoin")) {
            if (!sender.hasPermission("fake.join")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (args.length == 0) {
                sender.sendMessage(ChatColor.RED + "Please specify a name!");
                return true;
            }

            Bukkit.getServer().broadcastMessage(ChatColor.YELLOW + args[0] + " joined the game.");
        }

        if (cmd.getName().equalsIgnoreCase("broadcast")) {
            if (!sender.hasPermission("broadcast")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (args.length == 0) {
                sender.sendMessage(ChatColor.RED + "Please give a message to broadcast!");
                return true;
            }

            StringBuilder strbl = new StringBuilder();

            for (int i = 0; i < args.length; i++) {
                strbl.append(args[i] + " ");
            }

            String broadcastas = strbl.toString();
            Bukkit.getServer().broadcastMessage(ChatColor.WHITE + "[" + ChatColor.GOLD + "BROADCAST" + ChatColor.WHITE + "] " + ChatColor.RED + broadcastas);
        }

        if (cmd.getName().equalsIgnoreCase("heal")) {
            if (!sender.hasPermission("heal")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (!(sender instanceof Player)) {
                if (args.length == 0) {
                    sender.sendMessage(ChatColor.RED + "Please specify a player!");
                    return true;
                }

                Player target = Bukkit.getServer().getPlayer(args[0]);

                if (target == null) {
                    sender.sendMessage(ChatColor.RED + "Player must be online to be healed!");
                    return true;
                }

                target.setHealth(20);
                target.setFireTicks(0);
                target.sendMessage(ChatColor.GREEN + "CONSOLE" + " healed you!");
                sender.sendMessage(ChatColor.GREEN + target.getName() + " is healed!");

                return true;
            }
            if (sender instanceof Player) {
                if (args.length == 0) {
                    Player player = (Player) sender;
                    player.setHealth(20);
                    player.setFireTicks(0);
                    player.sendMessage(ChatColor.GREEN + "Your health is now full!");
                    return true;
                }

                Player target = Bukkit.getServer().getPlayer(args[0]);

                if (target == null) {
                    sender.sendMessage(ChatColor.RED + "Player must be online to be healed!");
                    return true;
                }

                Player player = (Player) sender;
                target.setHealth(20);
                target.setFireTicks(0);
                target.sendMessage(ChatColor.GREEN + player.getName() + " healed you!");
                player.sendMessage(ChatColor.GREEN + target.getName() + " is healed!");
            }
        }

        if (cmd.getName().equalsIgnoreCase("feed")) {
            if (!sender.hasPermission("feed")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }
            if (!(sender instanceof Player)) {
                if (args.length == 0) {
                    sender.sendMessage(ChatColor.RED + "Please specify a player!");
                    return true;
                }

                Player target = Bukkit.getServer().getPlayer(args[0]);

                if (target == null) {
                    sender.sendMessage(ChatColor.RED + "Player must be online to be fed!");
                    return true;
                }

                target.setHealth(20);
                target.setFireTicks(0);
                target.sendMessage(ChatColor.GREEN + "CONSOLE" + " fed you!");
                sender.sendMessage(ChatColor.GREEN + target.getName() + " hunger is now full!");

                return true;
            }

            if (sender instanceof Player) {
                if (args.length == 0) {
                    Player player = (Player) sender;
                    player.setFoodLevel(20);
                    player.sendMessage(ChatColor.GREEN + "Your hunger is now full!");

                    return true;
                }

                Player target = Bukkit.getServer().getPlayer(args[0]);

                if (target == null) {
                    Player player = (Player) sender;
                    player.sendMessage(ChatColor.RED + "Player must be online to be fed!");

                    return true;
                }

                Player player = (Player) sender;

                target.setFoodLevel(20);
                target.sendMessage(ChatColor.GREEN + player.getName() + " fed you!");
                player.sendMessage(ChatColor.GREEN + target.getName() + " hunger is now full!");
            }
        }

        if (cmd.getName().equalsIgnoreCase("tpall")) {
            if (!sender.hasPermission("teleport")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (!(sender instanceof Player)) {
                sender.sendMessage(ChatColor.RED + "Cannot teleport everyone to console!");
                return true;
            }

            if (sender instanceof Player) {
                if (args.length == 0) {
                    for (Player allplayers: Bukkit.getOnlinePlayers()) {
                        Player player = (Player) sender;
                        World w = player.getLocation().getWorld();
                        double x = player.getLocation().getX();
                        double y = player.getLocation().getY();
                        double z = player.getLocation().getZ();

                        allplayers.teleport(new Location(w, x, y, z));
                        player.sendMessage(ChatColor.GREEN + "All players teleported to you!");

                        return true;
                    }
                }

                for (Player allplayers: Bukkit.getOnlinePlayers()) {
                    Player target = Bukkit.getServer().getPlayer(args[0]);

                    if (target == null) {
                        Player player = (Player) sender;
                        player.sendMessage(ChatColor.RED + "Player must be online!");
                        return true;
                    }

                    Player player = (Player) sender;
                    World w = target.getLocation().getWorld();
                    double x = target.getLocation().getX();
                    double y = target.getLocation().getY();
                    double z = target.getLocation().getZ();

                    allplayers.teleport(new Location(w, x, y, z));
                    player.sendMessage(ChatColor.GREEN + "All players teleported to player!");

                    return true;
                }
            }
        }

        if (cmd.getName().equalsIgnoreCase("setspawn")) {
            if (!sender.hasPermission("setspawn")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (!(sender instanceof Player)) {
                sender.sendMessage(ChatColor.RED + "CONSOLE Cannot set spawn!");
                return true;
            }

            if (sender instanceof Player) {
                Player player = (Player) sender;

                getConfig().set("spawn.world", player.getLocation().getWorld());
                getConfig().set("spawn.x", player.getLocation().getX());
                getConfig().set("spawn.y", player.getLocation().getY());
                getConfig().set("spawn.z", player.getLocation().getZ());
                saveConfig();
                player.sendMessage(ChatColor.GREEN + "Spawn has been set!");

                return true;
            }
        }

        if (cmd.getName().equalsIgnoreCase("spawn")) {
            if (!sender.hasPermission("spawn")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (!(sender instanceof Player)) {
                sender.sendMessage(ChatColor.RED + "CONSOLE Cannot teleport to spawn!");
                return true;
            }

            if (getConfig().getConfigurationSection("spawn") == null) {
                Player player = (Player) sender;
                player.sendMessage(ChatColor.RED + "Spawn is not set!");
                return true;
            }

            if (sender instanceof Player) {
                Player player = (Player) sender;
                World w = Bukkit.getServer().getWorld(getConfig().getString("spawn.world"));
                double x = getConfig().getDouble("spawn.x");
                double y = getConfig().getDouble("spawn.y");
                double z = getConfig().getDouble("spawn.z");

                player.teleport(new Location(w, x, y, z));

                return true;
            }
        }

        if (cmd.getName().equalsIgnoreCase("kit")) {
            if (!(sender instanceof Player)) {
                sender.sendMessage(ChatColor.RED + "CONSOLE Cannot get kits!" + ChatColor.RED + "Kits:" + ChatColor.GOLD + "Starter");
                return true;
            }

            if (!sender.hasPermission("kit")) {
                sender.sendMessage(ChatColor.RED + "Access denied.");
                return true;
            }

            if (sender instanceof Player) {
                if (args.length == 0) {
                    Player player = (Player) sender;
                    player.sendMessage(ChatColor.RED + "Kits:" + ChatColor.GOLD + "Starter");
                    return true;
                }

                if (args[0].equalsIgnoreCase("starter")) {
                    if (!sender.hasPermission("kit.starter")) {
                        sender.sendMessage(ChatColor.RED + "Access denied.");
                        return true;
                    }

                    if (sender instanceof Player) {
                        Player player = (Player) sender;
                        PlayerInventory pinv = player.getInventory();
                        EconomyResponse withdraw = econ.withdrawPlayer(player.getName(), 10);

                         if (withdraw.transactionSuccess()) {
                            pinv.addItem(new ItemStack(Material.DIAMOND_PICKAXE, 1));
                            pinv.addItem(new ItemStack(Material.DIAMOND_SWORD, 1));
                            pinv.addItem(new ItemStack(Material.DIAMOND_AXE, 1));
                            pinv.addItem(new ItemStack(Material.COOKED_BEEF, 20));
                            return true;
                        } else {
                            player.sendMessage(ChatColor.RED + "You dont have required money ammount. Kit purchase failed!");
                            return true;
                        }
                    }
                }

                Player player = (Player) sender;
                player.sendMessage(ChatColor.RED + "Kit was not found. Do /kit for kits.");

                return true;
            }
        }

        return false;
    }
}

错误日志

8:54:05 AM [ERROR] null
8:54:05 AM org.bukkit.command.CommandException: Unhandled exception executing command 'spawn' in plugin UltimateCommandPack v1.0.0
8:54:05 AM at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:140) ~[bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at org.bukkit.craftbukkit.v1_8_R2.CraftServer.dispatchCommand(CraftServer.java:625) ~[bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.PlayerConnection.handleCommand(PlayerConnection.java:1077) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.PlayerConnection.a(PlayerConnection.java:937) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.PacketPlayInChat.a(SourceFile:37) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.PacketPlayInChat.a(SourceFile:9) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.PlayerConnectionUtils$1.run(SourceFile:13) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.7.0_75]
8:54:05 AM at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.7.0_75]
8:54:05 AM at net.minecraft.server.v1_8_R2.SystemUtils.a(SourceFile:60) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.MinecraftServer.A(MinecraftServer.java:670) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.DedicatedServer.A(DedicatedServer.java:336) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.MinecraftServer.z(MinecraftServer.java:626) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at net.minecraft.server.v1_8_R2.MinecraftServer.run(MinecraftServer.java:534) [bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at java.lang.Thread.run(Unknown Source) [?:1.7.0_75]
8:54:05 AM Caused by: java.lang.NullPointerException
8:54:05 AM at org.bukkit.craftbukkit.v1_8_R2.entity.CraftPlayer.teleport(CraftPlayer.java:464) ~[bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at org.bukkit.craftbukkit.v1_8_R2.entity.CraftEntity.teleport(CraftEntity.java:223) ~[bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM at me.herobrine112211.ulticmdpack.System.onCommand(System.java:313) ~[?:?]
8:54:05 AM at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[bukkit.jar:git-Bukkit-61ef214]
8:54:05 AM ... 15 more

我不知道它为什么不起作用。它看起来应该有效。如果你知道修复程序告诉我解决方案。感谢。

2 个答案:

答案 0 :(得分:2)

检查配置中spawn.world属性的值。如果世界不存在,那么w的值将为null

String worldName = getConfig().getString("spawn.world");
System.out.println(worldName); // Check if value is correct.
World w = Bukkit.getServer().getWorld(worldName);

修改

/setspawn命令中,您错误地设置了spawn.world配置值。

正如您在下面的评论中所解释的那样,您的spawn.world配置属性设置为:

spawn.world=CraftWorld{name=world}

实际应该是:

spawn.world=world

这是因为Location.getWorld()会返回WorldObject)而不是世界名称(String)。我正在检索name表示,而不是世界的toString()

World.getName()方法返回世界的唯一名称。

改变

getConfig().set("spawn.world", player.getLocation().getWorld());

到此

getConfig().set("spawn.world", player.getLocation().getWorld().getName());

getConfig().set(String,Object)方法将对象作为其第二个参数,因为您要传递ObjectWorld)以写入文件,所以Object&# 39; s toString()将被隐式调用。


备注

在我对您的问题进行初步调查之前收集了以下注释,然后再提供更多信息。

在以下帖子中,用户blackwolf12333必须确保从检索到的世界名称中删除换行符。更多信息可以在这里找到:

{{bukkit.org}} [Solved] Bukkit.getServer().getWorld(worldname) returns null?

此外,正如我的问题first comment中提到的Server.getWorld(String)不是线程安全的。请注意这一点。

答案 1 :(得分:0)

您收到NullPointerException,因为您将值world.toString()存储为世界名称,而不是world.getName()

if (cmd.getName().equalsIgnoreCase("setspawn")) {
  if (sender instanceof Player) {
    Player player = (Player) sender;

    getConfig().set("spawn.world", player.getLocation().getWorld());

在以下情况下抛出NullPointerException

  
      
  • 调用null对象的实例方法。
  •   
  • 访问或修改空对象的字段。
  •   
  • 将null的长度视为数组。
  •   
  • 访问或修改null的插槽,就像它是一个数组一样。
  •   
  • 抛出null,好像它是一个Throwable值。
  •   
     

(强调我的,来自documentation

尝试从配置中获取World时,会抛出NullPointerException,因为您使用world.toString()存储的世界不是有效的世界名称,因此不是名称任何世界。

String返回的world.toString()CraftWorld{name=myWorldName},这不是世界名称,世界名称为myWorldName(在此示例中)。如果您想解决此问题,则需要使用world.getName(),这将返回myWorldName的正确值。

因此,您的/setspawn代码应如下所示:

if (cmd.getName().equalsIgnoreCase("setspawn")) {
  //your code...
  if (sender instanceof Player) {
    Player player = (Player) sender;

    getConfig().set("spawn.world", player.getLocation().getName());
    //the rest of your code
  }
  //the rest of your code
  return true;
}