indiegamedev

Unity3D Game Engine – Unity3D – Inventory System – Send and Search into Inventory – JavaScript

Unity3D Game Engine – Unity3D – Inventory System – Send and Search into Inventory – JavaScript

Create a Scene with:

– Main Camera

– GameController (Empty game object), attach:
– GameControllerScript.js
– Inventory.js

– Cube, Sphere, Cylinder, attach:
– SendToInventory.js

Inventory.js


#pragma strict

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

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

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


GameControllerScript.js


#pragma strict

var displayInventory: GUIText; // Assign in Inspector

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

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

function Update(){
	displayInventory.text = "Inventory: " + Array(inventoryScript.inventory).ToString();//display inventory by converting it to an array
}// END Update()


SendToInventory.js


#pragma strict

var myName : String;// to store the object name

private var inventory : Inventory; // store the GameController>Inventory component

function Start () {

	myName = this.gameObject.name; // get the object name
	Debug.Log(myName);// show the name of this object
	
	// inserisco in una variabile l'oggetto con nome GameController, lo slash serve perchè non ha parent
    var gameControllerObject : GameObject = GameObject.Find ("/GameController");
    // se l'oggetto esiste lo inserisco in una variabile
    if (gameControllerObject != null)
    {
        inventory = gameControllerObject.GetComponent (Inventory);
    }
    // se l'oggetto non esiste restituisce un messaggio di errore
    if (gameControllerObject == null)
    {
        Debug.Log ("Cannot find 'Inventory' script");
    }
	
}// END Start()

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

function OnMouseDown ()
{
        inventory.inventory.Add(myName); // GameController>Inventory component.inventoryArrayList().Add(game object name)
        Destroy(gameObject); // destroy the game object because I have already sent it to the inventory
}// END OnMouseDown()

Play, click over Sphere, Cube, Cylinder, the inventory will be updated.

For italian peolple: come funziona?

1. Inventory.js
– dichiaro Array List(), il mio inventario

2. GameControllerScript.js
– ottiene il componente Inventory.js
– visualizza il contenuto dell’inventario

3. SendToInventory.js
– ottiene il componente Inventory.js
– al click del mouse sull’oggetto, invia il nome dell’oggetto corrente all’inventario
– distrugge l’oggetto appena inserito nell’inventario, per non rischiare di inserirlo due volte. Volendo si può anche semplicemente disabilitare il Collider per evitare la registrazione di altri click.

Search inside ArrayList

Change GameControllerScript.js:


#pragma strict

var displayInventory: GUIText; // Assign in Inspector

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

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

function Update(){
	displayInventory.text = "Inventory: " + Array(inventoryScript.inventory).ToString();//display inventory by converting it to an array

InventorySearch();
}// END Update()

function InventorySearch(){   
    
    // search string START ---------------- 
    var howBig = inventoryScript.inventory.Count;
    var n : int = 0;
	for (n = 0; n < howBig; n++){
	   if ( inventoryScript.inventory[n] == "Cube" )
	       Debug.Log("Find Cube");
	}
    // search string END ------------------
	
}// END InventorySearch()


Conver ArrayList to Array and Search inside Array

Change GameControllerScript.js:


#pragma strict

var displayInventory: GUIText; // Assign in Inspector

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

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

function Update(){
	displayInventory.text = "Inventory: " + Array(inventoryScript.inventory).ToString();//display inventory by converting it to an array

InventorySearch();
}// END Update()

function InventorySearch(){   
    
    // Convert ArrayList() to Array
    var newarr = new Array (Array(inventoryScript.inventory));
    Debug.Log(newarr);
    
        // search string START ---------------- 
        var n : int = 0;
	for (n = 0; n < newarr.length; n++){
	   if ( newarr[n] == "Cube" )
	       Debug.Log("Find Cube");
	}
	// search string END ------------------
	
}// END InventorySearch()


Notice:


function InventorySearch(){    
    
    // Convert ArrayList() to Array
    var newarr = new Array (Array(inventoryScript.inventory));
    Debug.Log(newarr);
    
        // search string START ---------------- 
        var n : int = 0;
	for (n = 0; n < newarr.length; n++){
	   if ( newarr[n] == "Cube" )
	       Debug.Log("Find Cube");
	}
	// search string END ------------------
	
}// END InventorySearch()

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D Game Engine – Unity3D – Inventory System – Send and Search into Inventory – JavaScript

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 – 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 – 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

Unity3D – Generic List – JavaScript

Unity3D – Generic List – JavaScript

The Generic List (also known as List) is similar to the JS Array and the ArrayList, the significant difference with the Generic List, is that you explicitly specify the type to be used when you declare it – in this case, the type of object that the List will contain.

Once you’ve declared it, you can only add objects of the correct type – and because of this restriction, you get two significant benefits:
– no need to do any type casting of the values when you come to retrieve them.
– performs significantly faster than ArrayList (5x faster)

Sample code:


#pragma strict

// you need to add a line at the top of any script in which you want to use Generic List
import System.Collections.Generic;

var someNumbers = new List.<int>();            // a real-world example of declaring a List of 'ints'
var enemies = new List.<GameObject>();         // a real-world example of declaring a List of 'GameObjects'
var vtcs = new List.<Vector3>(mesh.vertices);  // convert an array to a list

function Start(){

	myList.Add(theItem);                   // add an item to the end of the List
	myList[i] = newItem;                   // change the value in the List at position i
	var thisItem = List[i];                // retrieve the item at position i
	myList.RemoveAt(i);                    // remove the item from position i
	
	numList = nums.ToList();               // convert an array to list
	
}// END Start()

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

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

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Generic List – JavaScript