- Home /
How do you initialize a List or Array?
I'd like to know how to initialize a generic list.
I have mylist=new List.<String>();
I can't put mylist[14]="hello"; //because it doesn't exist yet.
mylist.Insert(14,"hello"); //same problem?
Do I have to initialize the list somehow?
I tried using things I've seen in a search like ([1..40]) but unity doesn't recognize them.
I can't figure out how to initialize the list with placeholders.
Answer by rutter · Mar 06, 2012 at 03:03 AM
Looks like your list is created, but empty.
myList.Add("hello");
Answer by Eric5h5 · Mar 06, 2012 at 02:31 AM
You did initialize it; that's what "`mylist=new List.();`" does. To add content, use the Add function. http://msdn.microsoft.com/en-us/library/s6hkc2c4(v=vs.80).aspx
$$anonymous$$aybe initialize is the wrong term. I'm trying to add a value at a specific position. I don't have values for positions 0,1,2,3 only 14. The other values will come in later.
The positions in a List don't exist until you add something. Sounds like you want to use myArray = new String[15];
ins$$anonymous$$d.
I get an error when trying that: Cannot convert 'UnityEngine.String[]' to 'System.Collections.Generic.List.'
I was hoping to be able to add values at certain positions and that other positions would be null and that I could check to see if a position has a value or is null.
The List"" is a first-in-first-out array. Using the Generics will cause it to start from zero and go from there. You would have to insert 14 other empty items into the list before getting to the 15th, where you could provide the value you are looking for.
If you are looking for creating a known size array and you plan on using the last one as you need to, I think you'd be better off creating a standard array String[15] as Eric5h5 said.
var mylist = new String[15]; myList[15] = "hello";
All of the other items will remain empty strings until you change them.
Your answer
Follow this Question
Related Questions
Remove and Add to List By Name aad 1 Answer
foreach a array inside a generic list 1 Answer
Converting Builtin Array to Generic List 2 Answers