Search Unity

Best method for rearranging and inserting items within an array

Discussion in 'Scripting' started by BigSeal, Dec 21, 2010.

  1. BigSeal

    BigSeal

    Joined:
    Jul 2, 2010
    Posts:
    26
    I have an inventory script that is an array of multiple different classes, and I want the player to be able to sort their items manually by dragging one on top of the other, and then having that first item be inserted in the inventory array before the item it was dragged on top of.

    I'm using a javascript array, and I noticed that there is not a command to insert a new item within the array, only to the start or end of it. I can think of a couple ways to do this under the given limitations, like removing all of items from the array and reinserting them in a new order, but this seems kind of brute force and unnecessary.

    It there a better way to do this?
     
  2. callahan.44

    callahan.44

    Joined:
    Jan 9, 2010
    Posts:
    694
    a) You could probably shuffle the array about, similar to a bubblesort. (quicker to swap pointers around than dealloc/alloc a new array)
    b) Use an array type that does have an Index Insert (like C#'s List<T>)
     
  3. BigSeal

    BigSeal

    Joined:
    Jul 2, 2010
    Posts:
    26
    Thanks for the reply. I figured I'm too far in to switch to a different array type, so I solved the issue by having items sorted on screen not by their position in the inventory array, but by a special InventoryID that gets assigned to them when they're added to the inventory and modified whenever an item is removed or added.
     
  4. trooper

    trooper

    Joined:
    Aug 21, 2009
    Posts:
    748
    This woulda worked if you were using generics...

    Code (csharp):
    1. List<string> inventory= new List<string>();
    2.  
    3. inventory.Add("Item1");
    4. inventory.Add("Item2");
    5. inventory.Add("Item3");
    6. inventory.Add("Item4");
    7.  
    8. // Move Item1 to bottom of list
    9. inventory.Remove("Item1");
    10. inventory.Insert(inventory.Count -1, "Item1");