-
Notifications
You must be signed in to change notification settings - Fork 14
/
Events.cs
78 lines (67 loc) · 2.1 KB
/
Events.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using UnityEngine;
using UnityEngine.Events;
public class Events : MonoBehaviour
{
private event Action<float> OnActionExecute = delegate { }; // Action-based event
private UnityEvent<float> OnUnityExecute; // UnityEvent-based event
private event EventHandler<CustomEventArgs> OnEventHandlerExecute; // EventHandler-based event
public class CustomEventArgs : EventArgs
{
public float Value { get; private set; }
public CustomEventArgs(float value) => Value = value;
}
void Start()
{
OnActionExecute += HandleActionEvent;
OnUnityExecute = new UnityEvent<float>();
OnUnityExecute.AddListener(HandleUnityEvent);
OnEventHandlerExecute += HandleEventHandler;
Debug.Log("Press 'I' for Action event, 'O' for UnityEvent, 'P' for EventHandler");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
TriggerActionEvent(1.0f);
}
if (Input.GetKeyDown(KeyCode.O))
{
TriggerUnityEvent(2.0f);
}
if (Input.GetKeyDown(KeyCode.P))
{
TriggerEventHandler(3.0f);
}
}
void TriggerActionEvent(float value)
{
OnActionExecute.Invoke(value);
}
void TriggerUnityEvent(float value)
{
OnUnityExecute.Invoke(value);
}
void TriggerEventHandler(float value)
{
OnEventHandlerExecute.Invoke(this, new CustomEventArgs(value));
}
void HandleActionEvent(float value)
{
Debug.Log($"Action Event triggered with value: {value}");
}
void HandleUnityEvent(float value)
{
Debug.Log($"UnityEvent triggered with value: {value}");
}
void HandleEventHandler(object sender, CustomEventArgs e)
{
Debug.Log($"EventHandler triggered by {sender} with value: {e.Value}");
}
void OnDestroy()
{
OnActionExecute -= HandleActionEvent;
OnUnityExecute.RemoveListener(HandleUnityEvent);
OnEventHandlerExecute -= HandleEventHandler;
}
}