unity3d

Unity 3D Game Engine – JavaScript – Interfaces

Unity 3D Game Engine – JavaScript – Interfaces

I ‘contratti’ di Interfaces permettono di aggiungere ad una classe nuove funzioni specificate all’interno di un’altra classe esterna.

Se 2 classi sono A padre->B figlio il figlio potrà usare le funzioni del padre
Se 2 classi hanno un contratto di Interface la classe A (interface) è estesa nelle funzioni dalla classe B (B implements A)

Le Interfaces vengono dichiarate con ‘I maiuscola+lettera maiuscola+nome’, ad esempio IKillable, IDamageable etc…

Le interfaces sono utili quando dobbiamo mettere in relazioni classi che non ha senso considerare padre-figlio. Ad esempio una classe Muro e una classe Auto non ha senso che siano padre-figlio, ma in comune potrebbero avere il fatto che entrambe possono essere danneggiate.

Interfaces.


#pragma strict

//This is a basic interface with a single required
//method.
public interface IKillable
{
    function Kill();
}

//Javascript does not allow generic types to
//be defined, so this version of IDamageable
//uses a float type
public interface IDamageable
{
    function Damage(damageTaken : float);
}

Avatar Class


#pragma strict

public class Avatar extends MonoBehaviour implements IKillable, IDamageable
{
    //The required method of the IKillable interface
    public function Kill()
    {
        //Do something fun
    }
    
    //The required method of the IDamageable interface
    public function Damage(damageTaken : float)
    {
        //Do something fun
    }
}

Come funziona?

1. Avatar Class
– classe pubblica Avatar implementa Interface IKillable
– funzione pubblica Kill() e Damage()

2. Interfaces
– public interface IKillable -> richiama la funzione Kill() da Avatar Class

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

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