Search Unity

Removing Elements in an Array

Discussion in 'Scripting' started by kidne, Jun 27, 2015.

  1. kidne

    kidne

    Joined:
    Nov 29, 2013
    Posts:
    25
    Is the only way to remove an element from an array by converting one of the elements into a list and then removing and replacing it? It's important that the element that I chose returns "null".
    selectedChar is an int chosen through checking is a Toggle isOn.

    Code (CSharp):
    1. System.Collections.Generic.List<myCharacters> list = new System.Collections.Generic.List<myCharacters>(selectedChar);
    2.         list.Remove(selectedChar);
    3.         selectedChar = list.ToArray();
    4.         //myCharacters.RemoveAt[selectedChar]; since this doesn't work.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    20,215
    There's a bunch of ways, but if what you have works in your case and is adequately performant, use it!

    You could (for instance) make a new array of the reduced size, copy over all elements before the one you are removing, and then copy over all elements after the one you're removing, and then assign the new array to the original array.

    There are also SQL-ish ways of doing it using the Linq extension methods, but these are frowned upon because if misused, they can tend to create a lot of memory allocations and hence heap garbage.
     
    kidne likes this.
  3. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    2,859
    If you need to add and remove elements, just use a list instead of an array in the first place.
     
    Kiwasi likes this.
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,788
    Yup. Don't use an array to do the job of a list. Right collection for the right job.
     
  5. kidne

    kidne

    Joined:
    Nov 29, 2013
    Posts:
    25
    Well, I couldn't use a list because the data that the array is accessing is being filled with data from my server across phpMyAdmin. I don't know if a List would work the same way through all the different scripts of code that I have for setting up a person's account, allowing them to register and download forms, sending emails etc. etc. Basically it's a ton of complicated code and I have no idea if a list would work as well as the .Net array!

    I ended up just setting the size of the array myself and then using a single variable from each element to determine if the element was "filled" or "not filled" and then overwriting or erasing that single variable and essentially the entire element itself. It seems to work exactly as I needed this way! This only worked out for me because I don't need people to be able to make a ton of elements. Four was just the number I needed, and if I need more I can just add it later myself to the physical code of the game. If however I wanted the array's size to change based on user input, I would definitely be using a List instead. Thank you everyone!
     
unityunity