Unity – Variables and Data Types

Public and Private

In Unity JavaScript it is not obligatory for every variable to declare – private or public –

Under:
1. without declarations the variable ‘myInt’ is public, you can use it anywhere in the code.
2. variable ‘ret’ is private because it is created inside a function, you can use it outside the function MultiplyByTwo()

#pragma strict

var myInt : int = 5;


function Start ()
{
    myInt = MultiplyByTwo(myInt);
    Debug.Log (myInt);
}


function MultiplyByTwo (number : int) : int
{
    var ret : int;
    ret = number * 2;
    return ret;
}

Under: it is better to declare – private or public – it is more professional and will make fewer mistakes!

#pragma strict

public var apples : int;
public var bananas : int;


private var stapler : int;
private var sellotape : int;


public function FruitMachine (a : int, b : int)
{
    var answer : int;
    answer = a + b;
    Debug.Log("Fruit total: " + answer);
}


private function OfficeSort (a : int, b : int)
{
    var answer : int;
    answer = a + b;
    Debug.Log("Office Supplies total: " + answer);
}

Data Types

Value
Contengono un valore
Cambiano solo se il valore della variabile viene cambiato in fase di scripting con una funzione

– int : interi
– float : numeri con la virgola
– double : it can hold very large (or small) numbers, the maximum and minimum values are 17 followed by 307 zeros.
– String : stringhe
– char : characters (caratteri alfanumerici)
– bool : TRUE Or FALSE
– Structs : strutture
-> Vector3
-> Vector2
-> Quaternion

Examples:

var hazardCount : int;
var spawnWait   : float;
var s           : String = "hello";
var gameOver    : boolean;
var spawnValues : Vector3;
var spawnValues : Vector3;
var cameraTarget : Transform;

Reference
Contengono un indirizzo di memoria con un valore che cambia nel tempo.
Ad esempio se la posizione di un oggetto cambia nel tempo anche la variabile di riferimento cambia, senza bisogno di utilizzare uno script. L’oggetto di riferimento viene assegnato all’interno di Inspector.

– Classes
-> Transform
-> GameObject

Examples:

// Assegnare da Inspector gli oggetti di riferimento
var mytext : GUIText;
var displayTime  : TextMesh; 
var theTextComponent : UI.Text; // store the Text component - Unity 4.6 or over
var theSliderComponent : UI.Slider; // store Slider component - Unity 4.6 or over
var MyInputField : UI.InputField; // store Slider component - Unity 4.6 or over
var myobject : GameObject;
var mycamera : Camera;
var mylight : Light;
var myaudio : AudioClip;

var myobjects : GameObject[]; // array di oggetti
var materials : Material[]; // array di materiali