Add ConfigurableEventManager implementation with example and guide
This commit is contained in:
81
Scripts/EventExample.cs
Normal file
81
Scripts/EventExample.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
using Godot;
|
||||
using EinSoftworks.Events;
|
||||
|
||||
namespace Voider;
|
||||
|
||||
/// <summary>
|
||||
/// Example script demonstrating how to use the ConfigurableEventManager.
|
||||
/// This would typically be attached to a Player, Enemy, or other game object.
|
||||
/// </summary>
|
||||
public partial class EventExample : Node
|
||||
{
|
||||
// Reference to the ConfigurableEventManager in the scene
|
||||
private ConfigurableEventManager _eventManager;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
// Get reference to the ConfigurableEventManager node
|
||||
// (Assumes it's named "EventManager" in your scene tree)
|
||||
_eventManager = GetNode<ConfigurableEventManager>("/root/Main/EventManager");
|
||||
|
||||
// Subscribe to events
|
||||
SubscribeToEvents();
|
||||
}
|
||||
|
||||
private void SubscribeToEvents()
|
||||
{
|
||||
// Example: Subscribe to a simple event with no parameters
|
||||
_eventManager.Subscribe("GameStarted", OnGameStarted);
|
||||
|
||||
// Example: Subscribe to an event with one parameter (int score)
|
||||
_eventManager.Subscribe<int>("ScoreChanged", OnScoreChanged);
|
||||
|
||||
// Example: Subscribe to an event with two parameters (string playerName, int level)
|
||||
_eventManager.Subscribe<string, int>("PlayerLevelUp", OnPlayerLevelUp);
|
||||
}
|
||||
|
||||
// Event handlers
|
||||
private void OnGameStarted()
|
||||
{
|
||||
GD.Print("Game has started!");
|
||||
}
|
||||
|
||||
private void OnScoreChanged(int newScore)
|
||||
{
|
||||
GD.Print($"Score changed to: {newScore}");
|
||||
}
|
||||
|
||||
private void OnPlayerLevelUp(string playerName, int newLevel)
|
||||
{
|
||||
GD.Print($"{playerName} leveled up to level {newLevel}!");
|
||||
}
|
||||
|
||||
// Example of raising events from code
|
||||
public void SomeGameAction()
|
||||
{
|
||||
// Raise an event with no parameters
|
||||
_eventManager.Raise("GameStarted");
|
||||
|
||||
// Raise an event with one parameter
|
||||
_eventManager.Raise("ScoreChanged", 100);
|
||||
|
||||
// Raise an event with two parameters
|
||||
_eventManager.Raise("PlayerLevelUp", "Player1", 5);
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
// Always unsubscribe when node is removed
|
||||
UnsubscribeFromEvents();
|
||||
}
|
||||
|
||||
private void UnsubscribeFromEvents()
|
||||
{
|
||||
if (_eventManager != null)
|
||||
{
|
||||
_eventManager.Unsubscribe("GameStarted", OnGameStarted);
|
||||
_eventManager.Unsubscribe<int>("ScoreChanged", OnScoreChanged);
|
||||
_eventManager.Unsubscribe<string, int>("PlayerLevelUp", OnPlayerLevelUp);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user