Skip to content

Instantly share code, notes, and snippets.

@daltonbr
Last active December 13, 2017 03:28
Show Gist options
  • Save daltonbr/d4cd0c036393288976b3c7410c88e623 to your computer and use it in GitHub Desktop.
Save daltonbr/d4cd0c036393288976b3c7410c88e623 to your computer and use it in GitHub Desktop.
A basic structure of a Delegate in C#
public class InventoryItemDisplay
{
public delegate void InventoryItemDisplayDelegate(InventoryItem item); // the signature of this delegate <void> <param item>
public static event InventoryItemDisplayDelegate onClick; // the event
public void Click()
{
Debug.Log("Clicked " + item.displayName);
if (onClick != null) // Important null check - if no one subscribes to this event, then it crashes.
{
onClick.Invoke(item); // inv
}
else
{
Debug.Log("Nobody was listening to " + item.displayName);
}
}
}
public class InventoryItemResponder : MonoBehviour
{
void Start ()
{
InventoryItemDisplay.onClick += HandleOnClick;
}
void OnDestroy ()
{
Debug.Log("Unsigned-up for onClick");
InventoryItemDisplay.onClick -= HandleOnClick;
}
void HandleOnClick (InventoryItem item)
{
Debug.Log ("Behold I have heard of a legendary item " + item.displayName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment