unity

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 Inheritance (Ereditarietà) – Intermediate – CSharp

How does classes Inheritance work in Unity?

Create an Empty Object and attach the scripts.

FruitSalad.cs


public class FruitSalad : MonoBehaviour // estende MonoBehaviour, è la classe dalla quale ereditano tutti i componenti dei nostri giochi
{
    void Start()
    {
        //Let's illustrate inheritance with the 
        
	     //default constructors.
        
        Debug.Log("Creating the fruit"); 
        
        Fruit myFruit = new Fruit();  
        
        Debug.Log("Creating the apple"); 
        
        Apple myApple = new Apple();  

        //Call the methods of the Fruit class.

        //Now let's illustrate inheritance with the 
        //constructors that read in a string.
        Debug.Log("Creating the fruit");
        
        myFruit = new Fruit("yellow");// crea un'istanza della classe Fruit.cs
        
        Debug.Log("Creating the apple");
        
        myApple = new Apple("green"); // crea un'istanza della classe Apple.cs

        //Call the methods of the Fruit class.
        myFruit.SayHello(); // scrive: Hello. I am a fruit.
        
        myFruit.Chop(); // scrive: The yellow fruit has been chopped

        //Call the methods of the Apple class.
        //Notice how class Apple has access to all
        //of the public methods of class Fruit.
        myApple.SayHello(); // scrive: Hello. I am a fruit.
        
        myApple.Chop(); // scrive: The green fruit has been chopped
    
     }

}

[/charp]

Fruit.cs



using UnityEngine;
using System.Collections;

//This is the base class which is
//also known as the Parent class.
public class Fruit 
{
    public string color;

    //This is the first constructor for the Fruit class
    //and is not inherited by any derived classes.
    public Fruit() // deve esserci obbligatoriamente il costruttore che riceve 0 parametri
    {
        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 Fruit(string newColor)
    {
        color = newColor;
        Debug.Log("2nd Fruit Constructor Called");
    }

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

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

Apple.cs


using UnityEngine;
using System.Collections;

//This is the derived class whis is
//also know as the Child class.
public class Apple : Fruit // Apple estende Fruit 
{
    //This is the first constructor for the Apple class.
    //It calls the parent constructor immediately, even
    //before it runs.
    public Apple() // deve esserci obbligatoriamente il costruttore che riceve 0 parametri
    {
        //Notice how Apple has access to the public variable
        //color, which is a part of the parent Fruit class.
        color = "red"; // la proprietà color è in Fruit.cs
        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 Apple(string newColor) : base(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");
    }
}


On console:

– Creating the fruit
– 1st Fruit Constructor Called

– Creating the apple
– 1st Fruit Constructor Called
– 1st Apple Constructor Called

– Creating the fruit
– 2nd Fruit Constructor Called

– Creating the apple
– 2nd Fruit Constructor Called
– 2nd Apple Constructor Called

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

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

For italian people:

1. Fruit myFruit = new Fruit(); -> public Fruit(), il costruttore senza parametri

2. Apple myApple = new Apple(); -> public Fruit() poi public Apple()

3. myFruit = new Fruit(“yellow”); -> public Fruit(string newColor)

4. myApple = new Apple(“green”); -> -> public Fruit(string newColor) poi public Apple(string newColor) : base(newColor) specifica la chiamata al costruttore di Fruit.cs tramite la keyword : base(newColor) – estende newColor

5. Fruit.cs scrive Debug.Log(“Hello, I am a fruit.”); e Debug.Log(“The ” + color + ” fruit has been chopped.”);

By |CSharp, Video Games Development|Commenti disabilitati su Unity Programming – Classes Inheritance (Ereditarietà) – Intermediate – CSharp

Unity Programming – Classes Overloading – Intermediate – CSharp

How does classes overloading work in Unity?

Create an ‘Empty Object’ and attack SomeOtherClass.cs


// SomeOtherClass.cs

using UnityEngine;
using System.Collections;

public class SomeOtherClass : MonoBehaviour
{
    void Start()
    {
        SomeClass myClass = new SomeClass();

        //The specific Add method called will depend on
        //the arguments passed in.
        int mysum = myClass.Add(1, 2);
        string mytext = myClass.Add("Hello ", "World");

        Debug.Log(mysum); // 3
        Debug.Log(mytext); // Hello World
    }

    public class SomeClass
    {
        //The first Add method has a signature of
        //"Add(int, int)". This signature must be unique.
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }

        //The second Add method has a sugnature of
        //"Add(string, string)". Again, this must be unique.
        public string Add(string str1, string str2)
        {
            return str1 + str2;
        }
    }
}

We have overloading when we call a class that has 2 or more methods with the same name.
In the script: – public int Add(int num1, int num2) – and – public string Add(string str1, string str2)
have the same name but the parameters are different and Unity can recognize them as unique.

Reference:
unity3d.com/learn/tutorials/topics/scripting/method-overloading?playlist=17117

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