Video Games Development

Unity – Destroy Components

Unity – Destroy Components

Removes a gameobject, component or asset.

DESTROY OBJECT

DRAG AND DROP to an object in the Hierarchy

#pragma strict

function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(gameObject);
    }
}

Run and press Key to destroy object

DELAY DESTRUCTION

DRAG AND DROP to an object in the Hierarchy

#pragma strict

function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(gameObject,3f);
    }
}

Run and press Key to destroy object after 3 seconds ‘3f’

DESTROY OTHER OBJECTS

1. DRAG AND DROP to an object in the Hierarchy

#pragma strict

public var other : GameObject;


function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(other);
    }
}

2. Inspector> variable ‘Other’> small icon to select an object to destroy (onother object)

DESTROY COMPONENTS WITHOUT REMOVE OBJECT

1.DRAG AND DROP to an object in the Hierarchy

#pragma strict

function Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        Destroy(GetComponent(SpriteRenderer));
    }
}

2. Play, look at ‘Inspector’, and press ‘Space Bar’, the component ‘Sprite Renderer’ will disappear.

DESTROY EVERYTHING AHHH!!!! – EXAMPLES LIST

        // Kills the game object
	Destroy (gameObject);

	// Removes this script instance from the game object
	Destroy (this);

	// Removes the rigidbody from the game object
	Destroy (rigidbody);
	
	// Kills the game object in 5 seconds after loading the object
	Destroy (gameObject, 5);

	// When the user presses Ctrl, it will remove the script 
	// named FooScript from the game object
	function Update () {
		if (Input.GetButton ("Fire1") && GetComponent (FooScript))
			Destroy (GetComponent (FooScript));
	}
By |Unity3D|Commenti disabilitati su Unity – Destroy Components

Unity – Enabling and Disabling Components

Unity – Enabling and Disabling Components

Attach this code to a light:

#pragma strict

private var myLight : Light;


function Start ()
{
    myLight = GetComponent(Light);
}


function Update ()
{
    if(Input.GetKeyUp(KeyCode.Space)) // click space bar to toggle light on/off
    {
        myLight.enabled = !myLight.enabled; // invert the status using not keyword
    }
}

Statemets:

myLight.enabled = myLight.enabled; -> light is enabled

myLight.enabled = !myLight.enabled; -> light is disabled, you can use not keyword ‘!’

By |Unity3D|Commenti disabilitati su Unity – Enabling and Disabling Components

Unity – Get Component

Unity – Get Component

Get the values of others components.

1. Create an Object

2. Assign to this object -> AnotherScript.js:

#pragma strict

public var playerScore : int = 9001;

3. Assign to the SAME OBJECT -> MainScript.js:

#pragma strict

private var anotherScript : AnotherScript;

function Awake ()
{
    anotherScript = GetComponent(AnotherScript);   
}


function Start ()
{
    Debug.Log("The player's score is " + anotherScript.playerScore);
  
}

The Result inside Console will be ‘The player’s score is 9001’

Notice:
Outside functions -> private var anotherScript : AnotherScript;
Inside Awake() -> anotherScript = GetComponent(AnotherScript); -> Statement: GetComponent(Component Name)
Inside Start() -> + anotherScript.playerScore -> Statement: variable of GetComponent.variable of Component

By |Unity3D|Commenti disabilitati su Unity – Get Component

Unity – Object Oriented Programming – OOP

Unity – Object Oriented Programming – OOP

OOP is the best way to organize your data.

NOTICE:
‘public class SingleCharacterScript’ -> deve avere lo stesso nome dello script senza l’estensione ‘SingleCharacterScript.js’

La classe è un contenitore per variabili e funzioni, ad esempio ‘public class Stuff’ contiene variabili e funzioni, è un buon modo per raggruppare cose che funzionano insieme.

Programmare in OOP significa dividere uno script in più script, ogniuno dei quali si occupa di uno specifico compito.

Qui sotto abbiamo:
– una porzione di codice ‘public class Stuff’ che contiene solo l’inventario dei proiettili, granate, missili.
– una per il movimento ‘function Movement ()’
– una per lo sparo ‘function Shoot ()’

Single Script

SingleCharacterScript.js

#pragma strict

public class SingleCharacterScript extends MonoBehaviour
{
    public class Stuff
    {
        public var bullets : int;
        public var grenades : int;
        public var rockets : int;
        
        public function Stuff(bul : int, gre : int, roc : int)
        {
            bullets = bul;
            grenades = gre;
            rockets = roc;
        }
    }
    
    
    public var myStuff : Stuff = new Stuff(10, 7, 25);
    public var speed : float;
    public var turnSpeed : float;
    public var bulletPrefab : Rigidbody;
    public var firePosition : Transform;
    public var bulletSpeed : float;
    
    
    function Update ()
    {
        Movement();
        Shoot();
    }
    
    
    function Movement ()
    {
        var forwardMovement : float = Input.GetAxis("Vertical") * speed * Time.deltaTime;
        var turnMovement : float = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
        
        transform.Translate(Vector3.forward * forwardMovement);
        transform.Rotate(Vector3.up * turnMovement);
    }
    
    
    function Shoot ()
    {
        if(Input.GetButtonDown("Fire1") && myStuff.bullets > 0)
        {
            var bulletInstance : Rigidbody = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation);
            bulletInstance.AddForce(firePosition.forward * bulletSpeed);
            myStuff.bullets--;
        }
    }
}

Split in Multiple Scripts

With OOP we can split the ‘SingleCharacterScript.js’ into Multiple Script:
– Inventory.js -> public class Inventory + subclass Stuff
– MovementControls.js -> variables and functions
– Shooting.js -> variables and functions

Look at Inventory.js

– main class ‘public class Inventory’
– sub class ‘public class Stuff’ nested inside ‘public class Inventory’
– variables ‘public var bullets : int; etc…’
– constructor ‘public function Stuff ()’ it needs the same name of the class ‘Stuff’, to assign default values to variables of a class

You can construct an object in this way:

public function Stuff () // assegno valori senza variare la tipologia di variabile
        {
            bullets = 1;
            grenades = 1;
            rockets = 1;
        }

Or in this way:

public function Stuff(bul : int, gre : int, roc : int) // specifico di che tipo di variabile si tratta
        {
            bullets = bul;
            grenades = gre;
            rockets = roc;
        }

Creare un’istanza delle variabili, praticamente un nuovo oggetto che si basa su uno già esistente.
Notare che ‘Stuff= new Stuff’ dove ‘Stuff’ è lo stesso nome della classe

public var myStuff : Stuff= new Stuff(50, 5, 5);

In caso di costruttori multipli:

public var myStuff : Stuff= new Stuff(50, 5, 5);
USERA’
public function Stuff(bul : int, gre : int, roc : int)
PERCHE’ I PARAMETRI CORRISPONDONO (notare int – int – float)

INVECE

public var myOtherStuff : Stuff= new Stuff(50, 1.5f);
USERA’
public function Stuff(bul : int, fu : float)
PERCHE’ I PARAMETRI CORRISPONDONO (notare int – float)

Attach the Multiple Script at the SAME OBJECT

Inventory.js

#pragma strict

public class Inventory extends MonoBehaviour
{
    public class Stuff // this is a subclass nested inside class Inventory
    {
        public var bullets : int;
        public var grenades : int;
        public var rockets : int;
        public var fuel : float;
        
        public function Stuff(bul : int, gre : int, roc : int)
        {
            bullets = bul;
            grenades = gre;
            rockets = roc;
        }
        
        public function Stuff(bul : int, fu : float)
        {
            bullets = bul;
            fuel = fu;
        }
        
        // Constructor
        public function Stuff ()
        {
            bullets = 1;
            grenades = 1;
            rockets = 1;
        }
    }
    
    
    // Creating an Instance (an Object) of the Stuff class
    public var myStuff : Stuff= new Stuff(50, 5, 5);
    
    public var myOtherStuff : Stuff= new Stuff(50, 1.5f);
    
    function Start ()
    {
        Debug.Log(myStuff.bullets); 
    }
}

MovementControls.js

#pragma strict

public var speed : float;
public var turnSpeed : float;


function Update ()
{
    Movement();
}


function Movement ()
{
    var forwardMovement : float = Input.GetAxis("Vertical") * speed * Time.deltaTime;
    var turnMovement : float = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
    
    transform.Translate(Vector3.forward * forwardMovement);
    transform.Rotate(Vector3.up * turnMovement);
}

Shooting.js

#pragma strict

public var bulletPrefab : Rigidbody;
public var firePosition : Transform;
public var bulletSpeed : float;


private var inventory : Inventory;


function Awake ()
{
    inventory = GetComponent(Inventory);
}


function Update ()
{
    Shoot();
}


function Shoot ()
{
    if(Input.GetButtonDown("Fire1") && inventory.myStuff.bullets > 0)
    {
        var bulletInstance : Rigidbody = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation);
        bulletInstance.AddForce(firePosition.forward * bulletSpeed);
        inventory.myStuff.bullets--;
    }
}
By |Unity3D|Commenti disabilitati su Unity – Object Oriented Programming – OOP

Unity – Functions

Unity – Functions

A function is a type of procedure or routine, a block of code inside curly braces {} that will be executed when “someone” calls it. Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. With functions you can write less code and do more!

The code:


#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;
}

It means:

function Start ()
Unity function. It is called when the unity object enters in the scene.
Start() function does not return anything.


var myInt : int = 5;

var – dichiaro che è una variabile – nome della variabile – myInt : tipo (intero) = 5 (valore inziale)


function MultiplyByTwo (number : int) : int … return ret;

function – dichiaro che è una funzione – nome della funzione ‘MultiplyByTwo’ – (creo una variabile temporanea ‘number’ : la variabile temporanea è un intero – int -) : il tipo della funzione è intero – int -, cioè il suo risultato sarà un numero intero … la funziona ritorna il valore della variabile ‘ret’;

NOTA: la variabile ‘number’ è privata della funzione ‘ MultiplyByTwo’ che la utilizza al solo fine di eseguire i suoi compiti, non è una variabile che posso richiamare al di fuori della funzione.


myInt = MultiplyByTwo(myInt);

Il nuovo valore della variabile ‘myInt’ lo ottengo mettendo in azione la funzione ‘ MultiplyByTwo’, in particolare invio alla funzione il valore di inizializzazione di ‘myInt’, cioè 5, la funzione assegna questo valore alla sua variabile temporanea privata ‘number’, esegue i calcoli e ritorna come risultato il valore di ‘ret’. Tornando all’inizio quindi ‘myInt’=’ret’ -> 10

By |Unity3D|Commenti disabilitati su Unity – Functions