Loops/ time intensive code in onCommand?

Discussion in 'Plugin Development' started by petrifiednightmares, Apr 13, 2011.

Thread Status:
Not open for further replies.
  1. Say I am making a plugin that gives the player 10 piles of different items on a command, I programmed it like this in onCommand:

    Code:
    if (commandLabel.equalsIgnoreCase("command"))
    {
        if (args.length > 0)
        {
            String name = args[1];
            Inventory in = plugin.getServer().getPlayer(name).getInventory();
            for (int i = 0; i < 27; i++)
            {
                ItemStack is = new ItemStack(itemId, amount);
                in.addItem(is);
            }
            return true;
        }
    Of course the problem here is that it lags out the game. What is the proper way to do this?
     
  2. Offline

    fullwall

    Instead of repeatedly creating objects that go to garbage instantly, try creating one ItemStack object first, and then just setting its id and amount in the loop.
     
  3. Offline

    Sammy

    It shouldn't lag the game/server :confused:
    What fullwall said is true but creating and object that goes to garbage instantly shouldn't be enough to lag the game =X

    Try to debug your plugin without having other plugins on... I really don't think that the problem resides on that for loop
     
  4. Oh I figured it out, the problem wasn't due to the loop lagging out minecraft. Instead, I had a bug in the item creation logic and it is generating incorrect itemIds. Is there a function like Block.isValidId(itemId) or something? Or do I have to hardcode the check to make sure the id is correct.
     
  5. Offline

    Sammy

    I think that if the value isn't valid the block will return null so just do a:
    Code:
    if(myBlock != null){
    //continue
    }
    else{
    //the blocks doesn't exist
    }
     
  6. Offline

    eisental

    you can check if an id is valid with:
    Code:
    if (Material.getMaterial(id)==null) {
       //invalid id
    }
    
     
Thread Status:
Not open for further replies.

Share This Page