Game Development Reference
In-Depth Information
What are delegates in C#? Imagine that you're able to create a variable and assign
it a function reference instead of a regular value. Having done this, you can invoke
the variable just like a function to call the referenced function at a later time. You can
even reassign the variable to reference a new and different function later. This, in
essence, is how delegates work. If you're familiar with C++, delegates are practically
equivalent to the function pointers. Thus, delegates are special types that can
reference and invoke functions. They're ideal to create extensible callback systems
and event notifications. For example, by keeping a list or array of delegate types,
potentially, many different classes can register themselves as listeners for callbacks
by adding themselves to the list. More information on C# can be found at http://
msdn.microsoft.com/en-gb/library/ms173171.aspx . Consider the following
code sample 2-8 for an example of the delegate usage in C# with Unity:
using UnityEngine;
using System.Collections;
//---------------------------------------------------
public class DelegateUsage : MonoBehaviour
{
//Defines delegate type: param list
public delegate void EventHandler(int Param1, int Param2);
//---------------------------------------------------
//Declare array of references to functions from Delegate type -
max 10 events
public EventHandler[] EH = new EventHandler[10];
//---------------------------------------------------
/// <summary>
/// Awake is called before start. Will add my Delegate
HandleMyEvent to list
/// </summary>
void Awake()
{
//Add my event (HandleMyEvent) to delegate list
EH[0] = HandleMyEvent;
}
//---------------------------------------------------
/// <summary>
/// Will cycle through delegate list and call all events
/// </summary>
void Start()
{
//Loop through all delegates in list
foreach(EventHandler e in EH)
{
//Call event here, if not null
if(e!=null)
 
Search WWH ::




Custom Search