-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent-system.cs
More file actions
50 lines (40 loc) · 1.34 KB
/
event-system.cs
File metadata and controls
50 lines (40 loc) · 1.34 KB
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
// C# Event System
// Decouple game systems using C# events and delegates.
// Prefer this over SendMessage/BroadcastMessage.
using System;
using UnityEngine;
namespace MyGame
{
public static class GameEvents
{
public static event Action<int> OnScoreChanged;
public static event Action OnGameOver;
public static event Action<Vector3> OnPlayerDied;
public static event Action<string, int> OnItemCollected;
public static void RaiseScoreChanged(int newScore)
=> OnScoreChanged?.Invoke(newScore);
public static void RaiseGameOver()
=> OnGameOver?.Invoke();
public static void RaisePlayerDied(Vector3 position)
=> OnPlayerDied?.Invoke(position);
public static void RaiseItemCollected(string itemName, int quantity)
=> OnItemCollected?.Invoke(itemName, quantity);
}
// Example subscriber
public class ScoreDisplay : MonoBehaviour
{
[SerializeField] private TMPro.TMP_Text _scoreText;
private void OnEnable()
{
GameEvents.OnScoreChanged += UpdateScore;
}
private void OnDisable()
{
GameEvents.OnScoreChanged -= UpdateScore;
}
private void UpdateScore(int score)
{
_scoreText.SetText("Score: {0}", score);
}
}
}