Videogames Development – Unity – Array

An Array stores multiple values in a single variable.
The first array’s value is 0.

There are two types of arrays in Unity:
1- builtin arrays and normal Javascript Arrays
2- builtin arrays (native .NET arrays), are extremely fast and efficient but they can not be resized

Javascript Arrays

Assign this code to an Empty Object in the Scene:

#pragma strict

function Start()
{
    
}

function Update()
{
// Array Start
var mycars = new Array();
mycars[0] = "Saab"; // Notice: the first value is 0
mycars[1] = "Volvo";
mycars[2] = "BMW";
// Array End
 var i= 1; // Array index
 Debug.Log(mycars[i]); // The result is Volvo
}

Javascript Arrays: Print an Array Content

#pragma strict

function Start () 
{
    var strings = ["First string", "Second string", "Third string"];
    
    for(var item : String in strings)
    {
        print (item);
    }
}

Javascript Arrays: basic use

var myArray = new Array();     // declaration
myArray.Add(anItem);           // add an item to the end of the array
var thisItem = myArray[i];     // retrieve an item from position i (richiamare un contenuto dalla posizione i)
myArray.RemoveAt(i);           // removes an item from position i
var howBig = myArray.length;   // get the length of the Array

.NET Arrays

Syntax 1 – multiple lines

#pragma strict

// type [] name = new Array type[number of items]
int[] myIntArray = new Array int[3];

function Start () 
{
// name of array[index] = value
myIntArray[0] = 12;
myIntArray[1] = 16;
myIntArray[2] = 18;
}

Syntax 2 – one line

#pragma strict

// type [] name = new Array type[number of items]
int[] myIntArray = {12, 16, 18};

function Start () 
{

}

Public Array – you can see them in Inspector window

The code below creates an Array of Game Objects with Tag ‘Player’

#pragma strict

public var players : GameObject[];

function Start ()
{
    players = GameObject.FindGameObjectsWithTag("Player");
    
    for(var i : int = 0; i < players.Length; i++)
    {
        Debug.Log("Player Number "+i+" is named "+players[i].name);
    }
}