x


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?

more ▼

asked Jun 24 '10 at 05:50 PM

LifeSizeDeity gravatar image

LifeSizeDeity
127 15 17 26

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.

Oct 13 '10 at 11:20 PM yoyo
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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");
}
more ▼

answered Jun 24 '10 at 06:03 PM

Peter G gravatar image

Peter G
15.1k 16 44 137

Thanks so much, that takes care of all my questions.

Jun 24 '10 at 08:28 PM LifeSizeDeity
(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Jun 24 '10 at 06:12 PM

Molix gravatar image

Molix
4.8k 17 27 66

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3420
x1396
x131

asked: Jun 24 '10 at 05:50 PM

Seen: 1950 times

Last Updated: Jun 24 '10 at 06:03 PM