delegate è la dichiarazione di un tipo delegato.
delegate è un tipo riferimento che può essere utilizzato per incapsulare un metodo.
In poche parole possiamo incapsulare o o più funzioni (multicast) all’interno di un songolo delegate.
Creare un Empty Object ed allegare lo script MulticastScript.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | using UnityEngine; using System.Collections; public class MulticastScript : MonoBehaviour { delegate void MultiDelegate(); MultiDelegate myMultiDelegate; // creo la variabile contenitore void Start() { myMultiDelegate += PowerUp; // aggiungo il metodo PowerUp() myMultiDelegate += TurnRed; // aggiungo il metodo TurnRed() if (myMultiDelegate != null ) // controllo che non sia nullo { myMultiDelegate(); // stampa Power UP! Turn to RED } myMultiDelegate -= PowerUp; // tolgo il metodo PowerUp() myMultiDelegate(); // Turn to RED } void PowerUp() { print( "Power UP!" ); } void TurnRed() { print( "Turn to RED" ); } } |
Con delegate possiamo incapsulare una singola funzione con parametri.
Creare un Empty Object ed allegare lo script DelegateScript.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using UnityEngine; using System.Collections; public class DelegateScript : MonoBehaviour { delegate void MyDelegate( int num); // creo il delegato con una proprietà int MyDelegate myDelegate; // notare che i nomi sono uguali void Start() { myDelegate = PrintNum; // assegno al delegato la funzione PrintNum() myDelegate(50); // invio a PrintNum(50) myDelegate = DoubleNum; myDelegate(50); } void PrintNum( int num) { print( "Print Num: " + num); } void DoubleNum( int num) { print( "Double Num: " + num * 2); } // print: // 50 // 100 } |