MysteryGM

Unity_C#EventExample

Jun 6th, 2021
632
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class GameManager: MonoBehaviour
  2. {
  3.     public delegate void OnCompleted();
  4.     public static event OnCompleted OnEndTurn;
  5.  
  6.     private void Update()
  7.     {
  8.         if (Input.GetButtonUp("Fire1"))
  9.         {
  10.             //Here I use the fire button to end the turn
  11.             if (OnEndTurn != null)
  12.             {
  13.                 //All the code you want to run before the turn ends goes here
  14.                 //.....
  15.                 OnEndTurn();
  16.             }
  17.         }
  18.     }
  19. }
  20.  
  21. //Now the listner
  22. public class Listner: MonoBehaviour
  23. {
  24.     void Start()
  25.     {
  26.         //Subscribe to the event
  27.         HelpOthers.OnEndTurn += WhatToDoWhenTurnEnds;
  28.     }
  29.  
  30.     void WhatToDoWhenTurnEnds()
  31.     {
  32.         print("I do this when turn ends");
  33.     }
  34. }
RAW Paste Data