Restore inventory from config on PlayerJoinEvent

Discussion in 'Spigot Plugin Development' started by gartenzaun, Jun 4, 2015.

  1. Hello guys,

    I want to restore a player's inventory from the config.yml:

    Listener:

    Code (Text):
        @EventHandler
        public void onPlayerJoin(PlayerJoinEvent event) {
            final Player p = event.getPlayer();
            restoreInventory(p);
        }
    Method restoreInventory():

    Code (Text):
    @SuppressWarnings("unchecked")
        public void restoreInventory(final Player player) {
             ArrayList<String> content = (ArrayList<String>) myPlugin.plugin.getConfig().get(player.getUniqueId().toString() + ".content");
             ArrayList<String> armor = (ArrayList<String>) myPlugin.plugin.getConfig().get(player.getUniqueId().toString() + ".armor");
             player.getInventory().setContents(content.toArray(new ItemStack[content.size()]));
             player.getInventory().setArmorContents(armor.toArray(new ItemStack[armor.size()]));
             player.updateInventory();
             myPlugin.plugin.getConfig().set(player.getUniqueId().toString() + ".content", null);
             myPlugin.plugin.getConfig().set(player.getUniqueId().toString() + ".armor", null);
             myPlugin.plugin.saveConfig();
             myPlugin.plugin.reloadConfig();
         }
    Example config:
    Code (Text):
    acooluuid:
      content:
      - ==: org.bukkit.inventory.ItemStack
        type: STONE
        amount: 64
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      - null
      armor:
      - ==: org.bukkit.inventory.ItemStack
        type: AIR
        damage: -1
        amount: 0
      - ==: org.bukkit.inventory.ItemStack
        type: AIR
        damage: -1
        amount: 0
      - ==: org.bukkit.inventory.ItemStack
        type: AIR
        damage: -1
        amount: 0
      - ==: org.bukkit.inventory.ItemStack
        type: AIR
        damage: -1
        amount: 0
    When I execute the method ingame without the PlayerJoinEvent it works and restores the whole inventory, but when I join on my server it doesn't restore the inventory. Did I do something wrong?

    Edit: There is no error in the console too
     
  2. PlayerJoinEvent is notorious for triggering early (before the player has fully joined the game). If you want to change a player's inventory on join, schedule a task for a few ticks later and it will work fine.
     
    • Useful Useful x 1
  3. on top of what the other dude said, use runTaskTimer with bukkit* runnables :)