Monday, June 27, 2011

Array usage in Unity scripting


Arrays allow you to store multiple objects in a single variable.
The Array class is only only available in Javascript. For more information about ArrayLists, Dictionaries or Hashtables in C# or Javascript see here
Here is a basic example of what you can do with an array class
function Start () {
var arr = new Array ();

// Add one element
arr.Push ("Hello");

// print the first element ("Hello")
print(arr[0]);

// Resize the array
arr.length = 2;
// Assign "World" to the second element
arr[1] = "World";

// iterate through the array
for (var value : String in arr) {
print(value);
}
}
There are two types of arrays in Unity, builtin arrays and normal Javascript Arrays.
Builtin arrays (native .NET arrays), are extremely fast and efficient but they can not be resized.
They are statically typed which allows them to be edited in the inspector. Here is a basic example of how you can use builtin arrays.
// Exposes an float array in the inspector,
// which you can edit there.
var values : float[];

function Start () {
// iterate through the array
for (var value in values) {
print(value);
}

// Since we can't resize builtin arrays
// we have to recreate the array to resize it
values = new float[10];

// assign the second element
values[1] = 5.0;
}

No comments:

Post a Comment