Use of Delegates and Events in unity, delegatesunity
How to create and use delegate Delegates to provide complex and dynamic functions on your script.
DelegateScript. cs
using UnityEngine;using System.Collections;public class DelegateScript : MonoBehaviour { delegate void MyDelegate(int num); MyDelegate myDelegate; void Start () { myDelegate = PrintNum; myDelegate(50); myDelegate = DoubleNum; myDelegate(50); } void PrintNum(int num) { print ("Print Num: " + num); } void DoubleNum(int num) { print ("Double Num: " + num * 2); }}
MulticastScript. cs
using UnityEngine;using System.Collections;public class MulticastScript : MonoBehaviour { delegate void MultiDelegate(); MultiDelegate myMultiDelegate; void Start () { myMultiDelegate += PowerUp; myMultiDelegate += TurnRed; if(myMultiDelegate != null) { myMultiDelegate(); } } void PowerUp() { print ("Orb is powering up!"); } void TurnRed() { renderer.material.color = Color.red; }}
How to create a dynamic "broadcast" system and use events.
EventManager. cs
using UnityEngine;using System.Collections;public class EventManager : MonoBehaviour { public delegate void ClickAction(); public static event ClickAction OnClicked; void OnGUI() { if(GUI.Button(new Rect(Screen.width / 2 - 50, 5, 100, 30), "Click")) { if(OnClicked != null) OnClicked(); } }}
TeleportScript. cs
using UnityEngine;using System.Collections;public class TeleportScript : MonoBehaviour { void OnEnable() { EventManager.OnClicked += Teleport; } void OnDisable() { EventManager.OnClicked -= Teleport; } void Teleport() { Vector3 pos = transform.position; pos.y = Random.Range(1.0f, 3.0f); transform.position = pos; }}
TurnColorScript. cs
using UnityEngine;using System.Collections;public class TurnColorScript : MonoBehaviour { void OnEnable() { EventManager.OnClicked += TurnColor; } void OnDisable() { EventManager.OnClicked -= TurnColor; } void TurnColor() { Color col = new Color(Random.value, Random.value, Random.value); renderer.material.color = col; }}
You can view: Unity3D-Use of the Delegate-SignalSlot information slot and replace SendMessage.