Last active
December 13, 2017 03:28
-
-
Save daltonbr/d4cd0c036393288976b3c7410c88e623 to your computer and use it in GitHub Desktop.
A basic structure of a Delegate in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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