Search Unity

Clearing array

Discussion in 'Scripting' started by User340, Apr 29, 2008.

  1. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    If I have an array with some empty slots, is there any function I can call which will remove them? I want to use something like Array.Clear () just Clear () removes everything and I just want to remove the empty slots. How can this be done?
     
  2. seon

    seon

    Joined:
    Jan 10, 2007
    Posts:
    1,441
    You will need to iterate through your array and remove the holes manually. There is no built in "Remove Empty Slots" functionality.
     
  3. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Okay. This is what I have so far.

    Code (csharp):
    1. for (var i = 0; i < list.length; i++)
    2. {
    3.     if (i == null)
    4.     {
    5.         // This doesn't actually delete the slot.
    6.         list.RemoveAt (i)?
    7.     }
    8. }
    9.  
    Now my question is, How do I delete one slot of an array?
     
  4. jeffcraighead

    jeffcraighead

    Joined:
    Nov 15, 2006
    Posts:
    740
    How are you using the array so that you see the empty slots? The Array type shouldn't actually ever have null entries because it is a list, not a real array.
     
  5. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    The list is an array. I have 10 gameObjects in an array, so the length of the array is 10. After I destroyed 4 of those gameObjects I checked the array's length and it was still ten, so it must have some null slots. How can I get rid of only the empty slots so the length is 6?

    Thanks
     
  6. seon

    seon

    Joined:
    Jan 10, 2007
    Posts:
    1,441
    You would have to use...

    Code (csharp):
    1. for (var i = 0; i < list.length; i++)
    2. {
    3.    if (list[i] == null)
    4.    {
    5.       // This doesn't actually delete the slot.
    6.       list.RemoveAt (i)?
    7.    }
    8. }
     
  7. jeffcraighead

    jeffcraighead

    Joined:
    Nov 15, 2006
    Posts:
    740
    Why don't you just remove it from the list when you destroy the object using SendMessage? Then you won't have to go through this cleanup loop.
     
  8. JimmyH

    JimmyH

    Joined:
    Mar 28, 2008
    Posts:
    8
    If you did want some sort of clean loop you'll need to adjust the iterator and the amount of iterations to be performed. Removing an item from the array should change the length of the array (in JS).



    Code (csharp):
    1.  
    2. var n:int = list.length;
    3.  
    4. for (var i:int = 0; i < n; i++)
    5. {
    6.    if (list[i] == null)
    7.    {
    8.      list.RemoveAt(i);
    9.      i--;
    10.      n--;
    11.    }
    12. }
    13.  
     
  9. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Thanks everyone.

    That was exactly my problem. Thanks Seon.