- Home /
Why can't I push and pop from string array?
I have an array that I will use to store Strings and save that using PlayerPrefsX(ArrayPrefs2). I need to add and replace elements of this array a lot of times.
private var Array1 : String[]; private var Array2 = new Array();
If I use Array1 I cannot use any functions like push/pop!(Only function I get is Length :/ ) If I use Array2 I need to convert that to a String array to store it in PlayerPrefsX.
n I won't even open my mouth about how my 2D arrays suck! I am using Unityscript and I know I am missing something VERY FUNDAMENTAL. :(
@kumarsmurthy, you can use List for push and pop elements.
using UnityEngine; using System.Collections; using System.Collections.Generic; public class IntroScript : $$anonymous$$onoBehaviour {
List <string> iList;
// Use this for initialization
void Start ()
{
iList = new List<string>();
for(int i = 0;i<10;i++)
{
iList.Add("User_"+i);
}
for(int j = 0;j< iList.Count;j++)
{
print ("User at "+j +" is "+iList[j]);
}
iList.RemoveAt(5);
print ("After removing element");
for(int j1 = 0;j1< iList.Count;j1++)
{
print ("User at "+j1 +" is "+iList[j1]);
}
}
}
Answer by Eric5h5 · Jan 10, 2014 at 05:07 AM
Built-in arrays are fixed size and have no add/remove functions. Never use the Array class; it's obsolete (slow and untyped). Use a generic List instead. http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F ArrayPrefs2 only uses built-in arrays, but it's trivial to convert List to a built-in array and back.
Thank you Eric and Santosh for your replies. I did go through "Which kind of Array should I use" before I posted that question, BUT I didn't read the complete article and used built in arrays!! I have another question, if I use a generic List, is it possible to make that 2D in future?? I have 3 lists of variable lengths. Even though I can use 3 lists, I think it will reduce a lot of code if I can access it something like myArray[0][X].
I saw that I can use a JaggedArray but I am too scared to try that out just yet.