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

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’

Unity3D – JS Advanced – extends System.Object

Unity3D – JS Advanced – extends System.Object

System.Object is the class from which (generally speaking) everything in Unity is derived.
Every single other thing we build in Unity, derives from System.Object.
You can use this to display variables in the inspector similar to how a Vector3 shows up in the inspector.

Attach to an Empty Object this:


class Test extends System.Object {
	var p = 5;
	var c = Color.white;
}
var test = Test ();

Inspect the Inspector!
Click the white triangle on the left of ‘Test’ to espand and see P and C var.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – JS Advanced – extends System.Object