我正在构建游戏并尝试使用事件系统。这是它如何实现的主要思想:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blocker2
{
public delegate void OnPlayerMoved(PlayerMovedEvent e);
public delegate void OnPlayerSpawned(PlayerSpawnedEvent e);
public delegate void OnBlockBreak(BlockBreakEvent e);
public delegate void OnBlockPlaced(BlockPlacedEvent e);
public static class EventHandler
{
private static List<OnPlayerMoved> _onPlayerMoved;
private static List<OnPlayerSpawned> _onPlayerSpawned;
private static List<OnBlockBreak> _onBlockBreak;
private static List<OnBlockPlaced> _onBlockPlaced;
static EventHandler()
{
}
public static void Subscribe()
{
}
// -------------------------- Player Related Events --------------------------
public static void OnPlayerMoved(PlayerMovedEvent e)
{
foreach (OnPlayerMoved del in _onPlayerMoved)
{
del(e);
}
}
public static void OnPlayerSpawned(PlayerSpawnedEvent e)
{
foreach (OnPlayerSpawned del in _onPlayerSpawned)
{
del(e);
}
}
// -------------------------- Block Related Events --------------------------
public static void OnBlockBreak(BlockBreakEvent e)
{
foreach (OnBlockBreak del in _onBlockBreak)
{
del(e);
}
}
public static void OnBlockPlaced(BlockPlacedEvent e)
{
foreach (OnBlockPlaced del in _onBlockPlaced)
{
del(e);
}
}
}
}
而且还会有更多的事件发生,我认为这种方法会使代码变得非常非常复杂。有更好的方法吗?(考虑代码的性能和可维护性)。提前致谢!对不起,我的英语不好。