Skip to main content
 首页 » 编程设计

c#之C#中的游戏事件处理系统

2024年02月13日11daizhj

我正在构建游戏并尝试使用事件系统。 这是其实现方式的主要思想:

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); 
            } 
        } 
    } 
} 

而且还会有更多的事件,我认为这种方法会使代码变得非常非常复杂。有更好的方法吗? (考虑代码的性能和可维护性)。 先谢谢了! 抱歉我的英语不好。

请您参考如下方法:

你为什么不使用标准 C# events ?他们将以相同的方式处理这个问题,因为一个事件允许多个订阅者。

C# 中的标准事件机制允许多个订阅者订阅一个事件,并且看起来像:

public static event EventHandler<PlayerMovedEventArgs> PlayerMoved; 
 
// Often, you'll have a method to raise the event: 
public static void OnPlayerMoved(PlayerMovedEventArgs args) 
{ 
    var handler = PlayerMoved; 
    if (handler != null) 
        handler(null, args); 
} 

话虽这么说,但我建议将它们放在相关的类中,而不是让它们全部是全局/静态的。然后,您可能会将引发事件的方法设为该类的私有(private)方法,这将使您的设计更易于维护。

例如,PlayerMoved 事件可能更适合在代表您的世界(或世界的一部分)的某个类中,并且以非静态方式放在其中。