- Home /
Is there a way to declare an array without using a size?
This is just a question of the interaction between Unity3d and a c# script. Currently I am using a script that makes the call:
public int [] foo = new int[10];
The thing that's getting me is inside the inspector window, I am able to change the size of the array. Obviously its size must be dynamic, so I guess my question is: Is there a way to declare the array without assigning its size, since I can just change it in the inspector window anyways? Also, how would I get the size of the array if it were to be changed in the inspector?
Note that the size isn't actually dynamic, rather, when you "resize" the array in the editor it will actually create a new array (of the new length) and copy your old data into it.
Answer by Peter G · Jun 24, 2010 at 06:03 PM
There are several options.
1.. It sounds like what you want to do is just this. It creates an array that can be resized/ edited in the inspector.
public int[] foo;
2.. Or if you are trying to resize your array frequently in-game, you might want to consider using ArrayLists or GenericLists. Generic lists will show up in the inspector, but arraylists will not.
To access the size of an array use array.Length. To access the number of items in a generic list use list.Count.
ex.
if(foo.Length == 5) {
print("foo has 5 elements");
}
Thanks so much, that takes care of all my questions.
Answer by Molix · Jun 24, 2010 at 06:12 PM
To answer your second question you can get the size using the Length property, e.g.
int sizeOfArray = foo.Length;
Also, you can resize the built in arrays using static members of the Array class, e.g.
Array.Resize<int>( ref foo, foo.Length + 1 ); // increases array size by one
Though as mentioned, it is often easier to use List<> if you'll do that often. The nice thing about normal arrays is they're faster to access.
Your answer
Follow this Question
Related Questions
Picking a Random Order for Levers 1 Answer
Adding variables from all scripts 2 Answers
A problem with arrays 1 Answer
Different footstep sounds problem! 2 Answers
Instantiate duplicates script in subsequent Objects 2 Answers