gamedev

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

Unity3D – warning Messages – BCW0028: WARNING: Implicit downcast from ‘UnityEngine.Component’ to ‘UnityEngine.AudioSource’

Unity3D – warning Messages – BCW0028: WARNING: Implicit downcast from ‘UnityEngine.Component’ to ‘UnityEngine.AudioSource’

Implicit Downcast from… to…

BCW0028: WARNING: Implicit downcast from ‘UnityEngine.Component’ to ‘UnityEngine.AudioSource’

This script will generate the BCW0028 error:

...

// buttons[i] -> this is an Array of GameObject

...
// Assegno Audio INIZIO #############################################################################
function AssignAudio () {
  
	var audioSrc : AudioSource;
	
	for(var i : int = 0; i < buttons.Length; i++) // assegno a tutti gli oggetti nell'array l'audio
	    {
	      	// BCW0028: WARNING: Implicit downcast from 'UnityEngine.Component' to 'UnityEngine.AudioSource'.
	      	audioSrc = buttons[i].AddComponent ("AudioSource"); 
	      	

	      	
			buttons[i].audio.clip = buttonAudio0; // Add audio clip
			buttons[i].audio.playOnAwake = false; // not play on awake  
	    }

}// END AssignAudio()
// Assegno Audio FINE ###############################################################################
...

Solution: you should explicity cast the Components to AudioSource yourself using “as” like this:

Change the row:

audioSrc = buttons[i].AddComponent ("AudioSource");

with

audioSrc = buttons[i].AddComponent ("AudioSource") as AudioSource;
By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – warning Messages – BCW0028: WARNING: Implicit downcast from ‘UnityEngine.Component’ to ‘UnityEngine.AudioSource’