MySQL: Online
Load: Low
Sandbox: Running

在 CounterStrikeSharp 中响应游戏事件

游戏事件是游戏在发生某件事时发出的消息:玩家死亡、回合开始、炸弹被安放。大多数有趣的插件都是围绕事件构建的。在 CounterStrikeSharp 中,订阅一个事件只需要几行代码。

1

什么是事件

每个事件都有自己的类,名称以 Event 开头,例如 EventPlayerDeath 或 EventRoundStart,并携带事件的数据,比如谁死了、谁击杀了他。你的插件会得到一个方法,每次事件发生时都会调用它。

2

用特性订阅

最简单的方式是在方法上加 GameEventHandler 特性。方法接收事件并返回 HookResult。事件数据可以直接从事件对象中读取。

using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using Microsoft.Extensions.Logging;

public class EventsPlugin : BasePlugin
{
    public override string ModuleName => "Events Example";
    public override string ModuleVersion => "1.0.0";

    [GameEventHandler]    public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info)    {
        Logger.LogInformation("{Name} died", @event.Userid?.PlayerName);
        return HookResult.Continue;
    }
}
3

在代码中订阅

你也可以在 Load 方法中用 RegisterEventHandler 注册处理程序。效果相同,而当你只想在某些条件下订阅时,例如取决于配置,这种方式更合适。

public override void Load(bool hotReload)
{
    RegisterEventHandler<EventRoundStart>((@event, info) =>
    {
        Logger.LogInformation("Round started");
        return HookResult.Continue;
    });
}
4

Pre 与 Post

默认情况下,你的处理程序在游戏处理完事件之后运行(Post)。使用 HookMode.Pre 时,它会在此之前运行,这样你就能改变接下来发生的事,例如用 DontBroadcast 隐藏默认消息。除非确实需要干预,否则请使用 Post。

[GameEventHandler(HookMode.Pre)]
public HookResult OnPlayerDeathPre(EventPlayerDeath @event, GameEventInfo info)
{
    if ([email protected])
    {
        info.DontBroadcast = true;
    }

    return HookResult.Continue;
}
5

玩家可能为 null

Userid 之类的属性可能为空,例如玩家恰好在事件触发的瞬间退出,或者击杀者是世界本身。使用之前一定要检查 null,否则运气不好时会在回合进行到一半时抛出异常。

6

HookResult 的含义

Continue 让游戏正常继续,大多数情况下这是正确的返回值。Handled 告诉游戏你已经处理好了,而 Stop 会阻止其他处理程序运行。除非有特别的理由,否则请返回 Continue。

7

好习惯

处理程序运行在游戏的主线程上,所以要保持它们快速,千万不要在里面等待数据库或网络请求。插件卸载时不需要取消订阅,CounterStrikeSharp 会替你移除处理程序。事件列表及其字段,请查阅游戏事件文档。

这篇教程对你有帮助吗?

页面生成耗时 0.011 秒
CounterStrikeSharp Web Compiler V1.0 - 制作工具 由 RomaniaBarlap 为社区打造。