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

Unity Programming – Nested Classes – CSharp – Intermediate

How to access properties of a nested class from another script.
Accesso ad una proprietà all’interno di una classe annidata in uno script esterno.

Create an ‘Empty Object’ and attach the scripts:

– SomeClass.cs


using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour // deve essere MonoBehaviour anche questa o non funziona
{
    // proprietà della classe principale
    public int bullets = 10;

    // classe annidata
    
    [System.Serializable] // DEVO dichiarala Serializable o non si può accede da uno script esterno
    public class Something
    {
        // proprietà della classe annidata
        public int fuel = 15;
    }
    public Something Some; // la inserisco in una variabile
}

– SomeOtherClass.cs


using UnityEngine;
using System.Collections;

public class SomeOtherClass : MonoBehaviour
{
    void Start()
    {
        // il nome SomeClass è quello dello script SomeClass.cs
        SomeClass SomeClassScript = transform.GetComponent<SomeClass>();

        // variabile che contiene la classe principale . proprietà
        Debug.Log(SomeClassScript.bullets); // 10

                   // nomeScript.nomeVariabileClasse.proprietà
            Debug.Log(SomeClassScript.Some.fuel); // 15
    }
}

Come funziona?

1. SomeOtherClass.cs

– memorizza in una variabile lo script ottenuto con GetComponent
– richiama la proprietà della classe principale SomeClassScript.bullets
– richiama la proprietà della classe annidata SomeClassScript.Some.fuel

2. SomeClass.cs

– dichiaro l’accessibilità della classe dall’esterno serializzandola [System.Serializable]

– inserisco la classe in una variabile public Something Some
Posso notare che poi la chiamata sarà su – Some – SomeClassScript.Some.fuel

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

Unity Programming – Classes – Beginners – CSharp

How does classes work in Unity?

Create an ‘Empty Object’ and attack Inventory.cs


// Inventory.cs

using UnityEngine;
using System.Collections;

public class Inventory : MonoBehaviour // il nome del file e della classe sono uguali
{
    // Creating an Instance (an Object) of the Stuff class
    public Stuff myStuff = new Stuff(10, 20, 30, 40); // il nome dell'oggetto è uguale al nome della classe è uguale al costruttore
    // We can create infinite Instances
    public Stuff myOtherStuff = new Stuff(50, 60, 70, 80);
    public Stuff myOtherStuffTwo = new Stuff(); // senza parametri assegna i valori di default
    public Stuff myOtherStuffThree = new Stuff(10.2F); // in base alla natura dei parametri riconosce il metodo, qui cerca lo Stuff() che accetta FLOAT


    void Start()
    {
        Debug.Log(myStuff.bullets); // 10
        Debug.Log(myOtherStuff.grenades); // 60
        myOtherStuff.grenades = 100; // cambio il valore dell'oggetto
        Debug.Log(myOtherStuff.grenades); // 100
        Debug.Log(myOtherStuffTwo.grenades); // 2
        Debug.Log(myOtherStuffThree.magicEnergy); // 10.2

    }

    public class Stuff // nome della classe
    {
        // proprietà
        public int bullets;
        public int grenades;
        public int rockets;
        public int fuel;

        public float magicEnergy;

        // metodo con l'arrivo dei parametri
        public Stuff(int bul, int gre, int roc, int fue) // nome del costruttore uguale a quello della classe
        {
            bullets = bul;
            grenades = gre;
            rockets = roc;
            fuel = fue;
        }

        // metodo senza l'arrivo dei parametri
        public Stuff() // nome del costruttore uguale a quello della classe
        {
            bullets = 1;
            grenades = 2;
            rockets = 3;
            fuel = 4;
        }

        public Stuff(float magicen) {
            magicEnergy = magicen;
        }
    }
}// END Inventory : MonoBehaviour

Rules:

– Inventory.cs and public class Inventory have the same name

– public Stuff myStuff = new Stuff(10, 20, 30, 40); same name in the instance call Stuff

– public Stuff() same name for the method Stuff

– public Stuff myOtherStuffThree = new Stuff(10.2F); Unity recognize automatically the method he needs reading the type of parameters passed, this technique is called ‘Overloading’.

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

MVC – Programmazione Model View Controller

Symfony è basato sul modello di programmazione MVC. A differenza della programmazione classica dove potremo in una sola pagina programmare tutta la nostra applicazione nel modello MVC dividiamo il codice in Model (modello), View (vista), Controller (controllore).

Programmazione classica in un’unico script:

– difficile da mantenere perchè di difficile lettura
– impossibile da affidare a tecnici che non abbiano la conoscenza di tutti i linguaggi utilizzati


<?php
 
// Connessione e selezione del database
$link = mysql_connect('localhost', 'myuser', 'mypassword');
mysql_select_db('blog_db', $link);
 
// Esecuzione query SQL
$result = mysql_query('SELECT date, title FROM post', $link);
 
?>
 
<html>
  <head>
    <title>List of Posts</title>
  </head>
  <body>
   <h1>List of Posts</h1>
   <table>
     <tr><th>Date</th><th>Title</th></tr>
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "\t<tr>\n";
printf("\t\t<td> %s </td>\n", $row['date']);
printf("\t\t<td> %s </td>\n", $row['title']);
echo "\t</tr>\n";
}
?>
    </table>
  </body>
</html>
 
<?php
 
// Chiusura connessione
mysql_close($link);
 
?>

Pattern MVC

Per semplicità in questi esempi utilizziamo un paradigma di programmazione procedurate senza usare la programmazione orientata agli oggetti (OOP) con classi, metodi e proprietà.

model.php solo manipolazione dei dati


function getAllPosts()
{
  // Connessione al database
  $link = open_connection('localhost', 'myuser', 'mypassword');
 
  // Esecuzione query SQL
  $result = query_database('SELECT date, title FROM post', 'blog_db', $link);
 
  // Popolamento dell'array
  $posts = array();
  while ($row = fetch_results($result))
  {
     $posts[] = $row;
  }
 
  // Chiusura connessione
  close_connection($link);
 
  return $posts;
} 

astrazione del database per separare le query di connessione.
Si potrebbero scrivere diverse query in base al tipo di DB (MySQL, PostgreSQL) senza modificare model.php


<?php
 
function open_connection($host, $user, $password)
{
  return mysql_connect($host, $user, $password);
}
 
function close_connection($link)
{
  mysql_close($link);
}
 
function query_database($query, $database, $link)
{
  mysql_select_db($database, $link);
 
  return mysql_query($query, $link);
}
 
function fetch_results($result)
{
  return mysql_fetch_array($result, MYSQL_ASSOC);
}

view.php solo vista HTML


<html>
  <head>
    <title>List of Posts</title>
  </head>
  <body>
    <h1>List of Posts</h1>
    <table>
      <tr><th>Date</th><th>Title</th></tr>
    <?php foreach ($posts as $post): ?>
      <tr>
        <td><?php echo $post['date'] ?></td>
        <td><?php echo $post['title'] ?></td>
      </tr>
    <?php endforeach; ?>
    </table>
  </body>
</html>

index.php il controllore, gestisce la logica business, cioè preleva i dati dal model, li manipola, scrive nella view.


<?php
 
// Richiesta del modello
require_once('model.php');
 
// Recupero della lista dei post
$posts = getAllPosts();
 
// Richeista della vista
require('view.php');

La vista può essere suddivisa in:

– Layout


<html>
  <head>
    <title><?php echo $title ?></title>
  </head>
  <body>
    <?php include('mytemplate.php'); ?>
  </body>
</html>

– Template


<h1>List of Posts</h1>
<table>
<tr><th>Date</th><th>Title</th></tr>
<?php foreach ($posts as $post): ?>
  <tr>
    <td><?php echo $post['date'] ?></td>
    <td><?php echo $post['title'] ?></td>
  </tr>
<?php endforeach; ?>
</table>

In Symfony la struttira MVC sarà la seguente:

# Model layer
– Astrazione del Database
– Accesso ai Dati

# View layer
– Layout disposizione (tag comuni html, head, body, footer) in Symfony app\Resources\views\base.html.twig
– Template modello (codice specifico) in Symfony app\Resources\views\default

# Controller
– Front controller (è unico in tutta l’applicazione, sicurezza, configurazione) in Symfony web\app.php e app_dev.php
– Action (azioni specifiche di quella pagina), in Symfony src\AppBundle\Controller\ilcontrollerfile.php -> nomefunzioneAction()

Bibliografia:
symfony.com/legacy/doc/gentle-introduction/1_4/it/01-introducing-symfony

By |PHP, Symfony, Web Design|Commenti disabilitati su MVC – Programmazione Model View Controller