Sabotender

Delegate Example

Apr 1st, 2014 (edited)
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class DelegateExample : MonoBehaviour {
  5.     //the "method templates" that are used
  6.     public delegate void enterCombatEvent();
  7.     public delegate void exitCombatEvent();
  8.     //the listeners for the events
  9.     public static enterCombatEvent OnEnterCombat;
  10.     public static exitCombatEvent OnExitCombat;
  11.  
  12.     private bool isInCombat;
  13.  
  14.     //Call this method when the player encounters an enemy
  15.     public void EnterCombat() {
  16.         isInCombat = true;
  17.  
  18.         //call the method, all scripts that have a listener will be called
  19.         OnEnterCombat?.Invoke();
  20.     }
  21.  
  22.     //Call this method when there are no more enemies
  23.     public void ExitCombat() {
  24.         isInCombat = false;
  25.  
  26.         //call the method, all scripts that have a listener will be called
  27.         OnExitCombat?.Invoke();
  28.     }
  29. }
  30.  
  31.  
  32.  
  33.  
  34. public class OtherScript : MonoBehaviour {
  35.  
  36.     // Use this for initialization
  37.     void Start () {
  38.         DelegateExample.OnEnterCombat += CombatStart;
  39.         DelegateExample.OnExitCombat += CombatEnd;
  40.     }
  41.     void OnDestroy() {
  42.         DelegateExample.OnEnterCombat -= CombatStart;
  43.         DelegateExample.OnExitCombat -= CombatEnd;
  44.     }
  45.    
  46.     //this is called when the player enteres combat
  47.     void CombatStart () {
  48.         //start combat music
  49.     }
  50.  
  51.     //this is called when the player leaves combat
  52.     void CombatEnd () {
  53.         //start casual music
  54.     }
  55. }
Add Comment
Please, Sign In to add comment