Advertisement
MarcinKubat

EVENTS - publisher

Jun 5th, 2020
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System; // musimy użyć to
  5.  
  6. public class TestingEvents : MonoBehaviour
  7. {
  8.     public event EventHandler OnSpacePressed; //nazwa eventu "OnCośtam" np. "OnEnemyKilled"
  9.  
  10.  
  11.     // testujrmy z delefatem przekazując zmienną tyu int
  12.     public event TestEventDelegate OnIntEvent;
  13.     public delegate void TestEventDelegate(int i);
  14.     private int spaceCount;
  15.  
  16.  
  17.     // testujemy z delegatem void (bez paramteru)
  18.     public event Action OnActionEvent;
  19.  
  20.     // można również podać parametry, np:
  21.     public event Action<bool, int> OnActionEventWithParameters;
  22.  
  23.  
  24.  
  25.  
  26.  
  27.     void Start()
  28.     {
  29.  
  30.     }
  31.  
  32.  
  33.  
  34.     private void Update()
  35.     {
  36.         if(Input.GetKeyDown(KeyCode.Space)){
  37.  
  38.             //Space pressed!        //jeżeli wciśnięto spację, uruchamiamy event OnSpacePressed
  39.             OnSpacePressed?.Invoke(this, EventArgs.Empty);  // "?.Invoke" zastępuje sprawdzenie czy ktoś tego słucha
  40.                                                             // "this, EventArgs.Empty" używamy gdy nie wysyłamy argumentów
  41.                                                             // w tym przykładzie event jest wywoływany w Update pod spacją,
  42.                                                             // ale można go dać w dowolnym innym miejscu
  43.  
  44.                                                            
  45.             // turaj testujemy co innego    -   delegata używamy aby przesłać obiekt lub wartość
  46.             spaceCount++;
  47.             OnIntEvent?.Invoke(spaceCount);
  48.  
  49.             // tutaj testujrmy delegat action (void)
  50.             OnActionEvent?.Invoke();
  51.  
  52.             // action z parametrami
  53.             OnActionEventWithParameters?.Invoke(false, 666);
  54.  
  55.         }
  56.     }
  57.  
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement