Unity Programming – Extensions Methods – Intermediate – CSharp

I metodi di estensione consentono di “aggiungere” metodi ai tipi esistenti senza creare un nuovo tipo derivato, ricompilare o modificare in altro modo il tipo originale. I metodi di estensione sono uno speciale tipo di metodo statico.

Di solito si raggruppano tutti i metodi di estensione in una sola classe per comodità, ad esempio il reset dei parametri e altri metodi che vengono richiamati spesso all’interno del codice.

Creare un Empty Object ed allegare gli scripts:

– ExtensionMethods.cs


using UnityEngine;
using System.Collections;

//It is common to create a class to contain all of your
//extension methods. This class must be static.
public static class ExtensionMethods
{
    //Even though they are used like normal methods, extension
    //methods must be declared static. Notice that the first
    //parameter has the 'this' keyword followed by a Transform
    //variable. This variable denotes which class the extension
    //method becomes a part of.
    public static void ResetTransformation(this Transform trans)
    {
        trans.position = Vector3.zero;
        trans.localRotation = Quaternion.identity;
        trans.localScale = new Vector3(1, 1, 1);
    }
}

– SomeClass.cs


using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour 
{
    void Start () {
        //Notice how you pass no parameter into this
        //extension method even though you had one in the
        //method declaration. The transform object that
        //this method is called from automatically gets
        //passed in as the first parameter.
        transform.ResetTransformation();
    }
}

Notare come è facile richiamare il reset dell’oggetto – transform.ResetTransformation(); –

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Unity Programming – Extensions Methods – Intermediate – CSharp

Unity Programming – Interfaces – Intermediate – CSharp

Unity Programming – Interfaces – Intermediate – CSharp

Un’interfaccia è un gruppo completamente astratto di membri che può essere considerato come la definizione di un contratto: chi implementa una interfaccia si impegna a scrivere il codice per ciascun metodo.

La classe che implementa un’interfaccia deve fornire l’implementazione di TUTTI i suoi metodi e delle sue proprietà, in questo caso però non c’è bisogno della parola chiave override, è sufficiente che i metodi definiti abbiano lo stesso nome con cui sono dichiarati nell’interfaccia.

Le interfacce non possono avere dei loro metodi o proprietà ma servono per stabilire delle relazioni tra le classi.

Nel caso di classi avremo CLASSE A padre -> eredita -> CLASSE B figlio.

Nel caso delle interfacce avremo INTERFACCIA A -> CLASSE B che implementa i metodi indicati nell’interfaccia.

Le interfacce si usano al posto dell’ereditarietà quando non ha senso impostare una parentela fra le classi. Ad esempio MURO ed AUTO non possono avere una relazione di parentela, ma possono essere accumunate dall’interfaccia DANNEGGIABILE

DANNEGGIABILE -> MURO

DANNEGGIABILE -> AUTO

L’interfaccia viene dichiarata con I maiuscola + maiuscola nome interfaccia

Creiamo un Empty Object e alleghiamo gli scripts:

– Interfaces.cs


using UnityEngine;
using System.Collections;

//This is a basic interface with a single required
//method.

public interface IKillable
	{
	void Kill();
	}

//This is a generic interface where T is a placeholder
//for a data type that will be provided by the 
//implementing class.

public interface IDamageable<T>
	{
	void Damage(T damageTaken);
	}

– Avatar.cs


using UnityEngine;
using System.Collections;

public class Avatar : MonoBehaviour, IKillable, IDamageable<float>
{
	//The required method of the IKillable interface
	public void Kill()
	{
	//Do something fun
	}

	//The required method of the IDamageable interface
	public void Damage(float damageTaken)
	{
	//Do something fun
	}
}

Avatar eredita da MonoBehaviour o estende MonoBehaviour ed implementa IKillable e IDamageable.
Ogni classe che implementa IKillable e IDamageable dovrà avere void Kill() e void Damage().
L’interfaccia è utile per dare regole ben precise nella costruzione delle classi, specialmente se sono affidate a team differenti.

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Unity Programming – Interfaces – Intermediate – CSharp

Unity Programming – Classes – Overriding – Intermediate – CSharp

Create an Empty Object abd attach this scripts:

– WarBand.cs


using UnityEngine;
using System.Collections;

public class WarBand : MonoBehaviour // banda 
{
    
void Start()
    	{
   
	Humanoid human = new Humanoid(); // istanzio
        
        Humanoid enemy = new Enemy();
        
        Humanoid orc = new Orc();

        //Notice how each Humanoid variable contains
        //a reference to a different class in the
        //inheritance hierarchy, yet each of them
        //calls the Humanoid Yell() method.
        human.Yell(); // scrive Humanoid version of the Yell() method
        
        enemy.Yell(); // scrive Humanoid version of the Yell() method
        
        orc.Yell();   // scrive Humanoid version of the Yell() method  
    
	}

}

– Humanoid.cs


using UnityEngine;
using System.Collections;

public class Humanoid
{
    
	//Base version of the Yell method
    
	public virtual void Yell() // urlo
    
	{
        
	Debug.Log("Humanoid version of the Yell() method");
    
	}

}

– Enemy.cs


using UnityEngine;
using System.Collections;

public class Enemy : Humanoid
{
    	//This hides the Humanoid version.
    	public override void Yell()
    	{
	base.Yell();
    	Debug.Log("Enemy version of the Yell() method");
    	}
}

– Orc.cs


using UnityEngine;
using System.Collections;

public class Orc : Enemy

{
    
	//This hides the Enemy version.
    
	public override void Yell()
    
	{
  
	base.Yell();     
	Debug.Log("Orc version of the Yell() method");
    
	}

}

Console:
Humanoid version of the Yell() method
-> stampato da human.Yell();

Humanoid version of the Yell() method
-> stampato da enemy.Yell();
Enemy version of the Yell() method

Humanoid version of the Yell() method
-> stampato da orc.Yell();
Enemy version of the Yell() method

Orc version of the Yell() method

For italian people, come funziona?

Abbiamo una ereditarietà tra Humanoids -> Enemy -> Orcs e tre metodi con lo stesso nome
Dichiarando la funzione con la keyword – override – prende il sopravvento questo metodo, se voglio con base.Yell(); posso aggiungere il metodo padre

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Unity Programming – Classes – Overriding – Intermediate – CSharp

Unity Programming – Classes – Member Hiding – Intermediate – CSharp

Create an Empty Object abd attach this scripts:

– WarBand.cs


using UnityEngine;

using System.Collections;



public class WarBand : MonoBehaviour // banda da guerra
{
    
void Start()
    	{
   
	Humanoid human = new Humanoid(); // istanzio
        
        Humanoid enemy = new Enemy();
        
        Humanoid orc = new Orc();

        //Notice how each Humanoid variable contains
        //a reference to a different class in the
        //inheritance hierarchy, yet each of them
        //calls the Humanoid Yell() method.
        human.Yell(); // scrive Humanoid version of the Yell() method
        
        enemy.Yell(); // scrive Humanoid version of the Yell() method
        
        orc.Yell();   // scrive Humanoid version of the Yell() method  
    
	}

}

– Humanoid.cs


using UnityEngine;

using System.Collections;



public class Humanoid
{
    
	//Base version of the Yell method
    
	public void Yell() // urlo
    
	{
        
	Debug.Log("Humanoid version of the Yell() method");
    
	}

}

– Enemy.cs


using UnityEngine;
using System.Collections;

public class Enemy : Humanoid
{
    	//This hides the Humanoid version.
    	new public void Yell()
    	{
    	Debug.Log("Enemy version of the Yell() method");
    	}
}

– Orc.cs


using UnityEngine;

using System.Collections;



public class Orc : Enemy

{
    
	//This hides the Enemy version.
    
	new public void Yell()
    
	{
       
	Debug.Log("Orc version of the Yell() method");
    
	}

}

Console:
Humanoid version of the Yell() method

Humanoid version of the Yell() method

Humanoid version of the Yell() method

For italian people, come funziona?

Abbiamo una ereditarietà tra Humanoids -> Enemy -> Orcs e tre metodi con lo stesso nome
Dichiarando la funzione con la keyword – new – nascondiamo i metodi – new – in favore del metodo del padre – Humanoid.cs – che prende il sopravvento.

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Unity Programming – Classes – Member Hiding – Intermediate – CSharp

Unity Programming – Classes – Polymorphism – Downcasting – Intermediate – CSharp

Il termine polimorfismo indica la possibilità di definire metodi e proprietà con lo stesso nome, in modo che, ad esempio, una classe derivata possa ridefinire un metodo della classe base con lo stesso nome.

Create an empty object and attach the scripts:

Console:

– FruitSalad.cs


using UnityEngine;
using System.Collections;

public class FruitSalad : MonoBehaviour

{
    
void 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
        
        Fruit 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.
        Apple myApple = (Apple)myFruit;
        myApple.SayHello();
        
        myApple.Chop();
    }

}

– Fruit.cs


using UnityEngine;
using System.Collections;

public class Fruit
{
    
    public Fruit()
    
    {
        
    Debug.Log("1st Fruit Constructor Called");
    
    }

    public void Chop()
    
    {
        
    Debug.Log("The fruit has been chopped.");
    }

    public void SayHello()
    
    {
        
    Debug.Log("Hello, I am a fruit.");
    
    }

}

– Apple.cs


using UnityEngine;
using System.Collections;

public class Apple : Fruit
{
    
    public 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 new void Chop()
     
    {
        
    Debug.Log("The apple has been chopped.");
    }

    public new void SayHello()
    
    {
        
    Debug.Log("Hello, I am an apple.");
    
    }

}

– 1st Fruit Constructor Called
– 1st Apple Constructor Called

– Hello, I am a fruit
– The fruit has been chopped

– Hello, I am an apple
– The apple has been chopped

For italian people, come funziona?

1. Polimorfismo: Apple viene memorizzata in Fruit
Fruit myFruit = new Apple(); Crea un’istanza della classe Apple(), si attiva il costruttore senza parametri della classe padre -> public Fruit() e della classe figlia -> public Apple()

2.
myFruit.SayHello();
-> Hello, I am a fruit
myFruit.Chop(); -> The fruit has been chopped

3. Downcasting: Apple dentro a MyFruit torna ad essere Apple
Apple myApple = (Apple)myFruit;
myApple.SayHello();
-> Hello, I am an apple
myApple.Chop(); -> The apple has been chopped

Un esempio game:
– Polimorfismo: ‘Goblin’ memorizzato in ‘Nemici’
– Downcasting: Goblin in Nemici torna Goblin

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Unity Programming – Classes – Polymorphism – Downcasting – Intermediate – CSharp