Unity3D – Inventory System – Basic

Unity3D – Inventory System – Basic

You need an Inventory System for your last FPS or for your graphic adventure?
This is the basic code to start!

Create a scene:

– Empty Object, rename it ‘GameController’ and attach:
– Inventory.js
– GameControllerScript.js

Inventory.js:


#pragma strict

var inventory = new ArrayList(); // declare the ArrayList

function Start () {
}// END Start()

function Update () {	
}// END Update()

GameControllerScript.js


#pragma strict

private var inventoryScript : Inventory; // variable to store another script
 
function Awake ()
{
    inventoryScript = GetComponent(Inventory); // get script 'Inventory'  
}// END Awake()

function Start(){
    // add to script 'Inventory'> var inventory = new ArrayList();
    inventoryScript.inventory.Add("pistol"); //add item to inventory
    inventoryScript.inventory.AddRange(Array("key", "key", "ammo", "ammo")); //add multiple items
    inventoryScript.inventory.Sort(); //sort inventory
    inventoryScript.inventory.Remove("ammo"); //remove first instance of item
}// END Start()
 
function OnGUI(){
    //display inventory by converting it to an array
    GUI.Label(Rect(0,0,400,50), "Inventory: " + Array(inventoryScript.inventory)); 
    // the result is -> Inventory: ammo,key,key,pistol
}// END OnGUI()

Play, the result is -> Inventory: ammo,key,key,pistol

For italian peolple: Come funziona?

Super facile, creo un’ArrayList() ed aggiungo e tolgo contenuti.
ArrayList() è 5 volte meno performante di un Built-in Arrays ma estremamente più dinamico infatti:
– ha una dimensione dinamica, per aggiungere e togliere contenuto dinamicamente
– accetta dati di tipo misto
– presenta funzioni più avanzate di JS Arrays vedi documentazione Microsoft ufficiale a:
http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Inventory System – Basic

Unity3D – 2D Array – 2D Grid of GameObjects

Unity3D – 2D Array – 2D Grid of GameObjects

2D Grid of GameObjects

Create a scene with:

– Sphere
– EmptyGameObject and assign Grid.js:


#pragma strict
 
var  oggetto:GameObject; // Assign in Inspector
var  griglia:GameObject[,];
 
function Start () {
 
	griglia = new GameObject[5,5];// 
	 
	for (var i=0;i<5;i++)
	 
	{
	   
	    for(var j=0;j<5;j++)
	    {
	 
	    griglia[i,j] = oggetto;
	    Instantiate(griglia[i,j],Vector3(i,0,j),Quaternion.identity); // Add 1 units 
	    print(griglia);
	   
	    }
	 
	}
}// END Start()

DRAG AND DROP Sphere over the slot of var oggetto

Play

You will see a grid of Spheres of 5×5 units, the pattern is:

OOOOO
OOOOO
OOOOO
OOOOO
OOOOO

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – 2D Array – 2D Grid of GameObjects

Unity3D – Multidimensional Arrays – Jagged Arrays

Unity3D – Multidimensional Arrays – Jagged Arrays

One Dimensional Array

A 1D (one dimensional) Array is something like that:


var strings = ["First string", "Second string", "Third string"];

or if you want:


// Array Start
var mycars = new Array();
mycars[0] = "Saab"; // Notice: the first value is 0
mycars[1] = "Volvo";
mycars[2] = "BMW";
// Array End

Debug.Log(mycars[0]); // Result is Saab

Notice the index inside square brackets [i], has only one dimension.

Try to think about a line:

[0] [1] [2]

OR

[Saab] [Volvo] [Bmw]

Multidimensional Array

A Multidimensional Array has a two dimensional grid coordinated to store variables.

A Multidimensional Array is always rectangular!

Example ONE:


#pragma strict
 
public var multiDimensionalArray: int[,] = new int[2,2]; // 2x2 -> 4 cells
 
function Start () {
 
// Array Values
multiDimensionalArray[0,0] = 10;
multiDimensionalArray[0,1] = 20;
multiDimensionalArray[1,0] = 30;
multiDimensionalArray[1,1] = 40;

Debug.Log(multiDimensionalArray[0,1]); // Result is 20
  
}// END Start()

NOTICE new int[2,2]; -> it means 4 cells

Try to think about a grid with 2D coordinates, the 4 cells are:

[0,0][0,1]
[1,0][1,1]

OR

[10][20]
[30][40]

Example TWO:


#pragma strict
 
public var multiDimensionalArray: int[,,] = new int[2,2,2]; 
 
function Start () {
 
// Array Values
multiDimensionalArray[0,0,0] = 10;
multiDimensionalArray[0,0,1] = 20;
multiDimensionalArray[0,1,0] = 30;
multiDimensionalArray[0,1,1] = 40;
multiDimensionalArray[1,0,0] = 50;
multiDimensionalArray[1,0,1] = 60;
multiDimensionalArray[1,1,0] = 70;
multiDimensionalArray[1,1,1] = 80;

Debug.Log(multiDimensionalArray[1,0,1]); // Result is 60
  
}// END Start()

Jagged Array (Matrici Irregolari o Array ‘Frastagliati’)

A Multidimensional Array is always rectangular, in a Jagged Array, each of the ‘rows’ is a different length


#pragma strict
 
public var myJaggedlArray = [
[0,1,1,0],
[1,0,0,1],
[1,0,0,1],
[0,1,1,0]
];
 
function Start () {
  
}// END Start()

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Multidimensional Arrays – Jagged Arrays

Unity3D – Game Engine – Shuffle an Array – Fisher–Yates shuffle

Unity3D – Game Engine – Shuffle an Array – Fisher–Yates shuffle

In game programming shuffle (mischiare) an array is useful to shuffle cards, bonus locations and so on…

The most used is the Fisher–Yates shuffle (named after Ronald Fisher and Frank Yates), also known as the Knuth shuffle (after Donald Knuth), is an algorithm for generating a random permutation of a finite set—in plain terms, for randomly shuffling the set.

The general rule is:

To shuffle an array a of n elements (indices 0..n-1):
for i from n – 1 downto 1 do
j ? random integer with 0 = j = i
exchange a[j] and a[i]

Let’s go on!

Create a scene with a Main Camera and attach the script “ArrayShuffle.js”:


#pragma strict

// Array Start
var uniqueCard  = new Array();
uniqueCard [0] = "Card0"; // Notice: the first value is 0
uniqueCard [1] = "Card1";
uniqueCard [2] = "Card2";
uniqueCard [3] = "Card3";
uniqueCard [4] = "Card4";
uniqueCard [5] = "Card5";
uniqueCard [6] = "Card6";
uniqueCard [7] = "Card7";
uniqueCard [8] = "Card8";
uniqueCard [9] = "Card9";
// Array End

var usedCardLocation; // variabile per Shuffle() -> rimescolare l'Array

function Start () {

}

function Update () {

}

function OnGUI () {
   
    // print in console the array content
    if (GUI.Button (Rect (10,10,150,100), "Print the Array!")) {
        PrintArray();
    }
    // shuffle the array (rimescola l'array)
    if (GUI.Button (Rect (300,10,150,100), "Shuffle the Array!")) {
        Debug.Log("Shuffle");
        Shuffle();
    }
}

function Shuffle(){

// Randomize the order of index...
	
	// vediamo come funziona al primo ciclo del loop...
	// genera un loop pari alla lunghezza dell'array-1 perchè l'array ha l'indice che parte da zero
	for ( var c=0; c <= uniqueCard.length-1; c++)               // 1. per c = 0
	{
		var thisCard = Random.Range (c, uniqueCard.length); // 2. ad esempio thisCard=3 (crea un valore random compreso all'interno dell'indice dell'array) 
		usedCardLocation = uniqueCard ;                  // 3. usedCardLocation = uniqueCard [0]
		uniqueCard  = uniqueCard [thisCard];             // 4. uniqueCard [0] = uniqueCard [3]
		uniqueCard [thisCard] = usedCardLocation;           // 5. uniqueCard [3] = usedCardLocation
	}                                                           // 6. riprendo dal punto 3.
                                                                    // 3. uniqueCard [3] = uniqueCard [1] (perchè c++ ha incrementato c di 1 unità)
}// END Shuffle                                                     // si ripete per tutta la lunghezza dell'array...

function PrintArray(){
// not elegant but easy to understand...
Debug.Log(uniqueCard [0]); 
Debug.Log(uniqueCard [1]); 
Debug.Log(uniqueCard [2]); 
Debug.Log(uniqueCard [3]); 
Debug.Log(uniqueCard [4]); 
Debug.Log(uniqueCard [5]); 
Debug.Log(uniqueCard [6]); 
Debug.Log(uniqueCard [7]); 
Debug.Log(uniqueCard [8]); 
Debug.Log(uniqueCard [9]); 
}

Play, press ‘Print the Array!’ and watch Inspector, press ‘Shuffle the Array’, press ‘Print the Array!’ and watch Inspector.

For italian people, come funziona?


function Shuffle(){

// Randomize the order of index...
	
	// vediamo come funziona al primo ciclo del loop...
	// genera un loop pari alla lunghezza dell'array-1 perchè l'array ha l'indice che parte da zero
	for ( var c=0; c <= uniqueCard.length-1; c++)               // 1. per c = 0
	{
		var thisCard = Random.Range (c, uniqueCard.length); // 2. ad esempio thisCard=3 (crea un valore random compreso all'interno dell'indice dell'array) 
		usedCardLocation = uniqueCard ;                  // 3. usedCardLocation = uniqueCard [0]
		uniqueCard  = uniqueCard [thisCard];             // 4. uniqueCard [0] = uniqueCard [3]
		uniqueCard [thisCard] = usedCardLocation;           // 5. uniqueCard [3] = usedCardLocation
	}                                                           // 6. riprendo dal punto 3.
                                                                    // 3b. uniqueCard [3] = uniqueCard [1] (perchè c++ ha incrementato c di 1 unità)
}// END Shuffle   

Tutto si basa sulla permutazione tra i vari valori dell’array, nei commenti del codice al punto:
– 4. uniqueCard [0] = uniqueCard [3]
– al punto 3b uniqueCard [3] = uniqueCard [1]

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Game Engine – Shuffle an Array – Fisher–Yates shuffle

Unity3D – Game Engine – ArrayLists – JavaScript

Unity3D – Game Engine – ArrayLists – JavaScript

You have to know that:

– The ArrayList is a .Net class

– ArrayLists are dynamic in size, so you can add and remove items, and the array will grow and shrink in size to fit.

– ArrayLists are also untyped, so you can add items of any kind, including a mixture of types in the same ArrayList.

– ArrayLists are also similarly more costly when compared to the blazingly fast performance of built-in arrays.

– ArrayLists have a wider set of features compared to JS Arrays, although neither of their feature sets completely overlaps the other.

Basic Declaration & Use:


var myArrayList = new ArrayList();    // declaration
myArrayList.Add(anItem);              // add an item to the end of the array
myArrayList[i] = newValue;            // change the value stored at position i
var thisItem : TheType = myArray[i];  // retrieve an item from position i (note the required casting!)
myArray.RemoveAt(i);                  // remove an item from position i
var howBig = myArray.Count;           // get the length of the array

Original article: http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?

MSDN docs: http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Game Engine – ArrayLists – JavaScript