videogames development

Unity 3D Game Engine – JavaScript – Overriding

Unity 3D Game Engine – JavaScript – Overriding

Overriding è una pratica che consente di sovrascrivere un metodo della classe padre con un metodo della classe figlia.

Fruit Class


#pragma strict

public class Fruit 
{
    public function Fruit ()
    {
        Debug.Log("1st Fruit Constructor Called");
    }
    
    //Overriding members happens automatically in 
    //Javascript and doesn't require additional keywords
    public function Chop ()
    {
        Debug.Log("The fruit has been chopped.");     
    }
    
    public function SayHello ()
    {
        Debug.Log("Hello, I am a fruit.");
    }
}

Apple Class


#pragma strict

public class Apple extends Fruit 
{
    public function Apple ()
    {
        Debug.Log("1st Apple Constructor Called");
    }
    
    //Overriding members happens automatically in 
    //Javascript and doesn't require additional keywords
    public function Chop ()
    {
        super.Chop();
        Debug.Log("The apple has been chopped.");     
    }
    
    public function SayHello ()
    {
        super.SayHello();
        Debug.Log("Hello, I am an apple.");
    }
}

FruitSalad Class


#pragma strict

function Start () 
{
    var myApple = new Apple();
    
    //Notice that the Apple version of the methods
    //override the fruit versions. Also notice that
    //since the Apple versions call the Fruit version with
    //the "base" keyword, both are called.
    myApple.SayHello();
    myApple.Chop(); 
    
    //Overriding is also useful in a polymorphic situation.
    //Since the methods of the Fruit class are "virtual" and
    //the methods of the Apple class are "override", when we 
    //upcast an Apple into a Fruit, the Apple version of the 
    //Methods are used.
    var myFruit = new Apple();
    myFruit.SayHello();
    myFruit.Chop();
}

Come funziona?

1. Fruit Class
– una classe pubblica Fruit con le funzioni Fruit() – Chop() – SayHello()

2. Apple Class
– classe figlia di Fruit con le funzioni
– Apple()
– Chop()-> super.Chop()
– SayHello()-> super.SayHello()

3. FruitSalad Class
– la funzione Start() si avvia la caricamento dello script
– richiama Apple().SayHello() e Apple().Chop() -> che vanno in ovverride su Fruit().SayHello() e Fruit().Chop()

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – JavaScript – Overriding

Unity 3D Game Engine – Java Script – Polymorphism – Upcasting – Downcasting

Unity 3D Game Engine – Java Script – Polymorphism – Upcasting – Downcasting

Polymorphism – Upcasting – Downcasting vengono utilizzate per creare funzioni dinamiche tra classi legate da parentela padre-figlio.

Fruit Class


#pragma strict

public class Fruit 
{
    public function Fruit ()
    {
        Debug.Log("1st Fruit Constructor Called");
    }
    
    public function Chop ()
    {
        Debug.Log("The fruit has been chopped.");     
    }
    
    public function SayHello ()
    {
        Debug.Log("Hello, I am a fruit.");
    }
}

Apple Class


#pragma strict

public class Apple extends Fruit 
{
    public function Apple ()
    {
        Debug.Log("1st Apple Constructor Called");
    }
    
    //Apple has its own version of Chop() and SayHello(). 
    //When running the scripts, notice when Fruit's version
    //of these methods are called and when Apple's version
    //of these methods are called.
    //In this example, the "new" keyword is used to supress
    //warnings from Unity while not overriding the methods
    //in the Apple class.
    public function Chop ()
    {
        Debug.Log("The apple has been chopped.");     
    }
    
    public function SayHello ()
    {
        Debug.Log("Hello, I am an apple.");
    }
}

FruitSalad Class


#pragma strict

function Start () 
{
    //Notice here how the variable "myFruit" is of type
    //Fruit but is being assigned a reference to an Apple. This
    //works because of Polymorphism. Since an Apple is a Fruit,
    //this works just fine. While the Apple reference is stored
    //in a Fruit variable, it can only be used like a Fruit
    var myFruit = new Apple();

    myFruit.SayHello();
    myFruit.Chop();
    
    //This is called downcasting. The variable "myFruit" which is 
    //of type Fruit, actually contains a reference to an Apple. Therefore,
    //it can safely be turned back into an Apple variable. This allows
    //it to be used like an Apple, where before it could only be used
    //like a Fruit.
    var myApple = myFruit as Apple;
    
    myApple.SayHello();
    myApple.Chop(); 
}

Come funziona?

1. Fruit Class
– al suo interno ha i costruttori pubblici Fruit() – Chop() – SayHello()

2. Apple Class
– è una classe figlia di Fruit Class ‘… class Apple extends Fruit …’
– ha il proprio costruttore Chop() – SayHello()

3. FruitSalad Class
– la funzione Start() è la prima che si avvia al caricamento dello script
– richiama Apple().SayHello – Apple().Chop()
– fa il Downcasting a:


var myApple = myFruit as Apple;

quindi sarà richiamata Fruit().SayHello – Fruit().Chop()

Apple appartiene di sicuro alla categoria Fruit, ma non è detto che sia vero il contrario.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Java Script – Polymorphism – Upcasting – Downcasting

Unity 3D Game Engine – JavaScript – Inheritance (Ereditarietà)

Unity 3D Game Engine – JavaScript – Inheritance (Ereditarietà)

L’ereditarietà fra le classi serve per creare una relazione forte tra classi con rapporto padre-figlio.
La classe figlio potrà accedere a tutti i costruttori della classe padre.

Le classi potranno essere:
– padre public -> il figlio e anche tutte le altre classi non imparentate potranno accedere ai costruttori di funzione del padre
– padre private -> i costruttori nel padre postranno esistere ma il figlio non vi potrà accedere
– padre protected -> solo il figlio potrà accedere ai costruttori del padre

Un esempio tratto dal mondo dei videogiochi potrebbe essere:

Humanoid class

– Player class

– Enemies class
— Orc class
— Goblins class

Fruit Class


#pragma strict

public class Fruit (Frutta)
{
    public var color: String;
    
    //This is the first constructor for the Fruit class
    //and is not inherited by any derived classes.
    public function Fruit()
    {
        color = "orange";
        Debug.Log("1st Fruit Constructor Called");
    }
    
    //This is the second constructor for the Fruit class
    //and is not inherited by any derived classes.
    public function Fruit(newColor : String)
    {
        color = newColor;
        Debug.Log("2nd Fruit Constructor Called");
    }
    
    public function Chop()
    {
        Debug.Log("The " + color + " fruit has been chopped.");     
    }
    
    public function SayHello()
    {
        Debug.Log("Hello, I am a fruit.");
    }
}

Apple Class (Mele)


#pragma strict

//This is the derived class whis is
//also know as the Child class.
public class Apple extends Fruit 
{
    
    //This is the first constructor for the Apple class.
    //It calls the parent constructor immediately, even
    //before it runs.
    public function Apple()
    {
        //Notice how Apple has access to the public variable
        //color, which is a part of the parent Fruit class.
        color = "red";
        Debug.Log("1st Apple Constructor Called");
    }
    
    //This is the second constructor for the Apple class.
    //It specifies which parent constructor will be called
    //using the "base" keyword.
    public function Apple(newColor : String)
    {
        super(newColor);
    
        //Notice how this constructor doesn't set the color
        //since the base constructor sets the color that
        //is passed as an argument.
        Debug.Log("2nd Apple Constructor Called");
    }
    
}

FruitSalad Class (Insalata di frutta)


#pragma strict
    
function Start () 
{   
    //Let's illustrate inheritance with the 
    //default constructors.
    Debug.Log("Creating the fruit");
    var myFruit = new Fruit();
    Debug.Log("Creating the apple");
    var myApple = new Apple();
        
    //Call the methods of the Fruit class.
    myFruit.SayHello();
    myFruit.Chop();
        
    //Call the methods of the Apple class.
    //Notice how class Apple has access to all
    //of the public methods of class Fruit.
    myApple.SayHello();
    myApple.Chop();
        
    //Now let's illustrate inheritance with the 
    //constructors that read in a string.
    Debug.Log("Creating the fruit");
    myFruit = new Fruit("yellow");
    Debug.Log("Creating the apple");
    myApple = new Apple("green");
        
    //Call the methods of the Fruit class.
    myFruit.SayHello();
    myFruit.Chop();
        
    //Call the methods of the Apple class.
    //Notice how class Apple has access to all
    //of the public methods of class Fruit.
    myApple.SayHello();
    myApple.Chop();
}

Come funziona?

1. Fruit Class
– creo una classe pubblica perchè devo poter accedere ai dati da altre classi esterne
– creo una funzione pubblica Fruit() con all’interno la variabile ‘color’

2. Apple Class
– creo la classe pubblica Apple() figlia di Fruit()


... Apple extends Fruit  ...

– accede alla variabile pubblica ‘color’ della classe Fruit() e gli assegna il valore ‘red’
– ‘red’ viene inviato come una stringa a ‘newColor’ di public function Fruit(newColor : String)

3. FruitSalad Class (macedonia)
Per fare la macedonia dobbiamo mischiare il frutto ‘orange’ di Fruit() e quello ‘red’ di Apple().
– nella funzione Start() che viene eseguita all’avvio del programma richiamo:

– la classe Fruit(). funzione SayHello()
-> “Hello, I am a fruit.”

– la classe Fruit(). funzione Chop()
-> “The ” + orange + ” fruit has been chopped.”

– la classe Apple(). funzione SayHello() della classe padre
-> “Hello, I am a fruit.”

– la classe Apple(). funzione Chop() della classe padre
-> “The” + yellow + ” fruit has been chopped.”

Un’altro sistema consiste nell’inviare dellew stringhe alle classiu padre-figlio come segue:


    //Now let's illustrate inheritance with the 
    //constructors that read in a string.
    Debug.Log("Creating the fruit");
    myFruit = new Fruit("yellow");
    Debug.Log("Creating the apple");
    myApple = new Apple("green");
        
    //Call the methods of the Fruit class.
    myFruit.SayHello();
    myFruit.Chop();

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – JavaScript – Inheritance (Ereditarietà)

Unity 3D Game Engine – Method Overloading

Unity 3D Game Engine – Method Overloading

Metodo di sovraccarico.
Permette una funzione in grado di trattare definizioni multiple.
NOTA BENE: la natura dei dati passati alla funzione deve coincidere altrimenti verrà restituito un errore.

SomeClass


#pragma strict

public class SomeClass
{
    //The first Add method has a signature of
    //"Add(int, int)". This signature must be unique.
    function Add(num1 : int, num2 : int) : int
    {
        return num1 + num2;
    }
    
    //The second Add method has a sugnature of
    //"Add(string, string)". Again, this must be unique.
    function Add(str1 : String, str2 : String) : String
    {
        return str1 + str2;
    }
}

SomeOtherClass


#pragma strict

function Start () 
{
    var myClass = new SomeClass();
        
    //The specific Add method called will depend on
    //the arguments passed in.
    myClass.Add (1, 2);
    myClass.Add ("Hello ", "World");
}

Come funziona?

1. SomeOtherClass

– la variabile myClass richiama la classe pubblica SomeClass()
– SomeClass().Add richiama la funzione Add (o possiamo dire il metodo Add), spedendo o numeri o variabili

2. SomeClass

– viene richiamata la classe, poi il metodo numerico o stringa a seconda del tipo di variabile che arriva.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Method Overloading

Unity 3D Game Engine – JavaScripts – Statics

Unity 3D Game Engine – JavaScripts – Statics

Solitamente se una stessa variabile si trova all’interno di classi diverse, questa assume valori diversi per ogni classe.
Se una variabile è statica invece ha avrà lo stesso valore anche se appartiene a classi differenti.
Cambiare il valore di una variabile statica all’interno di una classe equivale a cambiarne il valore all’interno di tutte le altre classi.

Vediamo un esempio

Enemy


#pragma strict

public class Enemy
{
    //Static variables are shared across all instances
    //of a class.
    public static var enemyCount : int = 0;
    
    function Enemy()
    {
        //Increment the static variable to know how many
        //objects of this class have been created.
        enemyCount++;
    }
}

Game


#pragma strict

public class Game
{
    function Start () 
    {
        var enemy1 = new Enemy();
        var enemy2 = new Enemy();
        var enemy3 = new Enemy();
        
        //You can access a static variable by using the class name
        //and the dot operator.
        var x : int = Enemy.enemyCount;
    }
}

Player


#pragma strict

public class Player extends MonoBehaviour 
{
    //Static variables are shared across all instances
    //of a class. 
    public static var playerCount : int = 0;
    
    function Start()
    {
        //Increment the static variable to know how many
        //objects of this class have been created.
        playerCount++;
    }
}

PlayerManager


#pragma strict

function Start () 
{
    //You can access a static variable by using the class name
    //and the dot operator.
    var x : int = Player.playerCount;
}

Come funziona?

1. Enemy
– definisco una classe pubblica ‘Enemy’ perchè sia accessibile da qualunque script
– definisco una variabile statica ‘enemyCount’
– incremento di +1 ‘enemyCount’

2. Game
– definisco una classe pubblica ‘Game’
– all’inizio del gioco si avvia la funziona Start(), ogni variabile enemy1-2-3 avvia l’incremento del conteggio
– accedo alla variabile statica semplicemente con var x : int = Enemy.enemyCount; -> nomeclasse.nomevariabilestatica

3. Player
Funziona come Enemy definisce la variabile statica playerCount, poi la incrementa playerCount++

4. PlayerManager
– accedo alla variabile statica semplicemente con var x : int = Player.playerCount; -> nomeclasse.nomevariabilestatica

5. Utilities

Altri esempi

Utilities


#pragma strict

public static class Utilities 
{
    //A static method can be invoked without an object
    //of a class. Note that static methods cannot access
    //non-static member variables
    public static function Add(num1 : int, num2 : int) : int
    {
        return num1 + num2;
    }
}

UtilitiesExample


#pragma strict

function Start () 
{
    //You can access a static method by using the class name
    //and the dot operator.
    var x : int = Utilities.Add (5, 6);
}

Come funziona?

1. Utilities
– definisce una funzione statica

2. tilitiesExample
– spedisce i valori 5,6 alla classe pubblica statica Utilities.funzionepubblicastatica -> ritorna la somma 5+6 -> X = 11

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – JavaScripts – Statics