模组:制作指南/APIs/Events
阅读
2024-10-15更新
最新编辑:sizau
阅读:
更新日期:2024-10-15
最新编辑:sizau
← 模组:目录
不完整的翻译 本文或部分尚未完全翻译成中文。
欢迎您通过编辑帮助其建设。 |
SMAPI 提供了几个 C#事件,这些事件使模组在某些事情发生时(例如,玩家放置一个对象时)做出响应,或者定期运行代码(例如,每个更新周期一次)
常见问题
什么是事件(events) ?
事件使你可以在发生某些事情时运行代码。可以在引发“事件”(发生的情况)时添加任意数量的“事件处理程序”(调用方法)。 可以将事件和处理程序视为“when...then”语句:
存档已加载 <-- 事件 然后运行我的代码 <-- 事件处理程序
有关详细信息,请参阅C# 编程指南中的事件中的“事件”。
如何使用它们?
通常将事件处理程序添加到 Entry 方法中,可以随时添加和删除它们。例如,在每天开始时打印一条消息。首先,从下面的列表中选择适当的事件 (GameLoop.DayStarted), 然后添加一个事件处理程序,并在方法代码中执行以下操作:
/// <summary>模组的主要入口点。</summary>
public class ModEntry : Mod
{
/**********
** 公共方法
*********/
/// <summary>模组入口点,加载模组后自动调用</summary>
/// <param name="helper">提供用于编写模组的简化API</param>
public override void Entry(IModHelper helper)
{
// 事件 += 方法
helper.Events.GameLoop.DayStarted += this.OnDayStarted;
}
/**********
** 私有方法
*********/
/// <summary>在新的一天开始后调用的方法</summary>
/// <param name="sender">事件对象</param>
/// <param name="e">事件参数</param>
private void OnDayStarted(object sender, DayStartedEventArgs e)
{
this.Monitor.Log("新的一天到来了!");
}
}
提示:不需要记住方法参数。在 Visual Studio 中,输入 helper.Events.GameLoop.SaveLoaded +=
然后按 TAB 来自动生成方法
事件如何呈现到游戏中?
每次游戏计时(游戏更新其状态并呈现到屏幕时)都会引发事件,每秒60次。 一个事件可能会引发多次(例如,如果玩家同时按下两个键),但是大多数事件不会每秒引发60次(例如,玩家不太可能每秒按下60个按钮)
事件处理程序是“同步”运行的:游戏暂停时模组的代码不会运行,因此没有更改冲突的风险。由于代码运行非常迅速,因此除非你的代码异常缓慢,否则玩家不会注意到任何延迟。就是说,当使用诸如 UpdateTicked 或者 Rendered 应该缓存繁重的操作(例如加载资源),而不是在每个刻度中重复执行这些操作,以免影响性能。
如果模组更改了事件的发起?
事件根据游戏状态的快照引发,这通常是“但不一定”是当前游戏状态
例如,考虑这种情况:
- 菜单 GameMenu 打开了
- SMAPI 引发 MenuChanged 事件,并且模组 A 和 B 正在监听
- 模组 A 接收了事件并关闭了菜单
- 模组 B 接收了事件
每个模组仍在处理菜单打开的 MenuChanged 事件,即使第一个模组已将菜单关闭。SMAPI 将在下一个刻度时为关闭的菜单引发一个新的 MenuChanged 事件
这很少会影响模组,但是如果你需要当前状态,则需要牢记 (例如考虑用 Game1.activeClickableMenu 代替 e.NewMenu)
事件
可用的事件记录在下面
显示
this.Helper.Events.Display 具有链接到 UI 并绘制到屏幕的事件
事件 | 描述 | |||||||||
---|---|---|---|---|---|---|---|---|---|---|
#MenuChanged | 在打开、关闭或替换游戏菜单后引发
事件参数:
| |||||||||
#Rendering | 打开 sprite batch 同时,在游戏将任何内容绘制到屏幕上之前,触发此事件。在此事件触发后,sprite batch 可能多次关闭并重新打开。 但只在每次draw tick只会启动一次. 此事件对于在屏幕上绘制没有用, 因为游戏会在这之上覆盖绘制。
事件参数:
| |||||||||
#Rendered | 会在游戏的一个draw tick中对sprite batch进行绘制后,最后一个sprite batch在屏幕上渲染前启动。因为游戏可能会在一个draw tick中打开/关闭sprite batch多次,sprite batch可能没有包含正在绘制的所有内容,并且有些内容可能已经渲染在屏幕上了。在这个点上绘制到sprite batch的内容会覆盖在所有普通内容上(包括菜单,HUD,和光标)。
事件参数:
| |||||||||
#RenderingWorld | 在游戏事件绘制到屏幕之前启动。这个事件不对绘制有任何帮助,因为游戏绘制会覆盖它。
事件参数:
| |||||||||
#RenderedWorld | Raised after the game world is drawn to the sprite patch, before it's rendered to the screen. Content drawn to the sprite batch at this point will be drawn over the world, but under any active menu, HUD elements, or cursor.
事件参数:
| |||||||||
#RenderingActiveMenu | 当一个菜单被打开时 (Game1.activeClickableMenu != null), 在将该菜单绘制到屏幕上之前触发。这包括游戏的内部菜单,例如进入游戏时的主菜单。Content drawn to the sprite batch at this point will appear under the menu.
事件参数:
| |||||||||
#RenderedActiveMenu | When a menu is open (Game1.activeClickableMenu != null), raised after that menu is drawn to the sprite batch but before it's rendered to the screen. Content drawn to the sprite batch at this point will appear over the menu and menu cursor.
事件参数:
| |||||||||
#RenderingHud | Raised before drawing the HUD (item toolbar, clock, etc) to the screen. The vanilla HUD may be hidden at this point (e.g., because a menu is open). Content drawn to the sprite batch at this point will appear under the HUD.
事件参数:
| |||||||||
#RenderedHud | Raised after drawing the HUD (item toolbar, clock, etc) to the sprite batch, but before it's rendered to the screen. The vanilla HUD may be hidden at this point (e.g., because a menu is open). Content drawn to the sprite batch at this point will appear over the HUD.
事件参数:
| |||||||||
#WindowResized | Raised after the game window is resized.
事件参数:
|
游戏循环
this.Helper.Events.GameLoop has events linked to the game's update loop. The update loop runs roughly ≈60 times/second to run game logic like state changes, action handling, etc. These are often useful, but you should consider semantic events like Input where applicable.
event | summary | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
#GameLaunched | Raised after the game is launched, right before the first update tick. This happens once per game session (unrelated to loading saves). All mods are loaded and initialised at this point, so this is a good time to set up mod integrations. | ||||||||||||
#UpdateTicking UpdateTicked |
在游戏状态更新前/后启动(大约每秒钟60次)。
事件参数:
| ||||||||||||
#OneSecondUpdateTicking OneSecondUpdateTicked |
Raised before/after the game state is updated, once per second.
事件参数:
| ||||||||||||
#SaveCreating SaveCreated |
Raised before/after the game creates the save file (after the new-game intro). The save won't be written until all mods have finished handling this event. This is a somewhat specialised event, since the world isn't fully initialised at this point; in most cases you should use DayStarted, Saving, Saved instead. | ||||||||||||
#Saving Saved |
Raised before/after the game writes data to save file (except the initial save creation). The save won't be written until all mods have finished handling this event. This is also raised for farmhands in multiplayer. | ||||||||||||
#SaveLoaded | Raised after loading a save (including the first day after creating a new save), or connecting to a multiplayer world. This happens right before DayStarted; at this point the save file is read and Context.IsWorldReady is true.
This event isn't raised after saving; if you want to do something at the start of each day, see DayStarted instead. | ||||||||||||
#DayStarted | Raised after a new in-game day starts, or after connecting to a multiplayer world. Everything has already been initialised at this point. (To run code before the game sets up the day, see DayEnding instead.) | ||||||||||||
#DayEnding | Raised before the game ends the current day. This happens before it starts setting up the next day and before Saving. | ||||||||||||
#TimeChanged | Raised after the in-game clock time changes, which happens in intervals of ten in-game minutes.
事件参数:
| ||||||||||||
#ReturnedToTitle | Raised after the game returns to the title screen. |
输入
this.Helper.Events.Input has events raised when the player uses a controller, keyboard, or mouse in some way. They can be used with the input API to access more info or suppress input.
event | summary | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
#ButtonsChanged | Raised after the player pressed/released any buttons on the keyboard, mouse, or controller. This includes mouse clicks. If the player pressed/released multiple keys at once, this is only raised once.
事件参数:
| |||||||||||||||
#ButtonPressed ButtonReleased |
Raised after the player pressed/released a keyboard, mouse, or controller button. This includes mouse clicks. If the player pressed/released multiple keys at once, this is raised for each button pressed.
事件参数:
| |||||||||||||||
#CursorMoved | Raised after the player moves the in-game cursor.
事件参数:
| |||||||||||||||
#MouseWheelScrolled | Raised after the player scrolls the mouse wheel.
事件参数:
|
多人
this.Helper.Events.Multiplayer has events raised for multiplayer messages and connections.
event | summary | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
#PeerContextReceived | Raised after the mod context for a player is received. The event is raised for any player (whether host or farmhand), including when the connecting player doesn't have SMAPI installed. This is the earliest point where messages can be sent to the player via SMAPI.
This happens immediately before the game approves the connection, so the player doesn't exist in the game yet. When connecting to the host, contextual fields like Game1.IsMasterGame or Context.IsMultiplayer may not be set yet; you can check e.Peer.IsHost to know whether the current player is a farmhand, since the host context will always be received first. Assuming another mod doesn't block the connection, the connection will be approved on the next tick. 事件参数:
| |||||||||||||||
#PeerConnected | Raised after a connection from another player is approved by the game. The event is raised for any player (whether host or farmhand), including when the connecting player doesn't have SMAPI installed. This happens after PeerContextReceived.
The player is connected to the game at this point, so methods like Game1.server.kick will work. 事件参数:
| |||||||||||||||
#ModMessageReceived | Raised after a mod message is received over the network.
事件参数:
| |||||||||||||||
#PeerDisconnected | Raised after the connection to a player is severed.
事件参数:
|
玩家
this.Helper.Events.Player has events raised when the player data changes.
Currently these events are only raised for the current player. That will likely change in a future version, so make sure to check e.IsLocalPlayer if you only want to handle the current player.
event | summary | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
#InventoryChanged | Raised after items are added or removed from the player inventory.
事件参数:
| ||||||||||||||||||
#LevelChanged | 在一个玩家技能等级发生变化后触发. 当玩家技能等级提升的第一时间立马触发 (不是在玩家睡觉后游戏提示时触发).
事件参数:
| ||||||||||||||||||
#Warped | 当玩家移动到新地点的时候触发(农场到车站,玩家所在矿井层数发生变化也算).
事件参数:
|
世界
this.Helper.Events.World has events raised when the in-game world changes in some way.
event | summary | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
#LocationListChanged | Raised after a game location is added or removed (including building interiors).
事件参数:
| ||||||||||||||||||
#BuildingListChanged | Raised after buildings are added/removed in any location.
This event isn't raised for buildings already present when a location is added. If you need to handle those too, use LocationListChanged and check e.Added.OfType<BuildableGameLocation>() → buildings. 事件参数:
| ||||||||||||||||||
#ChestInventoryChanged | Raised after items are added or removed from a chest's inventory.
事件参数:
| ||||||||||||||||||
#DebrisListChanged | Raised after debris is added/removed in any location (including dropped or spawned floating items).
This event isn't raised for debris already present when a location is added. If you need to handle those too, use LocationListChanged and check e.Added → debris. 事件参数:
| ||||||||||||||||||
#LargeTerrainFeatureListChanged | Raised after large terrain features (like bushes) are added/removed in any location.
This event isn't raised for large terrain features already present when a location is added. If you need to handle those too, use LocationListChanged and check e.Added → largeTerrainFeatures. 事件参数:
| ||||||||||||||||||
#NpcListChanged | Raised after NPCs are added/removed in any location (including villagers, horses, Junimos, monsters, and pets).
This event isn't raised for characters already present when a location is added. If you need to handle those too, use LocationListChanged and check e.Added → characters. 事件参数:
| ||||||||||||||||||
#ObjectListChanged | Raised after objects are added/removed in any location (including machines, furniture, fences, etc). For floating items, see DebrisListChanged.
This event isn't raised for objects already present when a location is added. If you need to handle those too, use LocationListChanged and check e.Added → objects. 事件参数:
| ||||||||||||||||||
#TerrainFeatureListChanged | Raised after terrain features are added/removed in any location (including trees, hoed dirt, and flooring). For bushes, see LargeTerrainFeatureListChanged.
This event isn't raised for terrain features already present when a location is added. If you need to handle those too, use LocationListChanged and check e.Added → terrainFeatures. 事件参数:
|
特殊
this.Helper.Events.Specialised 针对特殊情况的事件. 大多数模组不应使用这些功能
event | summary | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
#LoadStageChanged | Raised when the low-level stage in the game's loading process has changed, for mods which need to run code at specific points in the loading process. The available stages or when they happen might change without warning in future versions (e.g., due to changes in the game's load process), so mods using this event are more likely to break or have bugs. Most mods should use the game loop events instead.
事件参数:
| ||||||||||||
#UnvalidatedUpdateTicking UnvalidatedUpdateTicked |
Raised before/after the game updates its state (≈60 times per second), regardless of normal SMAPI validation. This event is not thread-safe and may be invoked while game logic is running asynchronously. Changes to game state in this method may crash the game or corrupt an in-progress save. Do not use this event unless you're fully aware of the context in which your code will be run. Using this event will trigger a warning in the SMAPI console.
事件参数:
|
进阶
变化监控
You may want to handle a change that doesn't have its own event (e.g., an in-game event ends, a letter is added to the mailbox, etc). You can usually do that by handling a general event like UpdateTicked, and detecting when the value(s) you're watching changed. For example, here's a complete mod which logs a message when an in-game event ends:
/// <summary>The main entry point for the mod.</summary>
public class ModEntry : Mod
{
/*********
** Fields
*********/
/// <summary>The in-game event detected on the last update tick.</summary>
private Event LastEvent;
/*********
** Public methods
*********/
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// <param name="helper">Provides simplified APIs for writing mods.</param>
public override void Entry(IModHelper helper)
{
helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked;
}
/*********
** Private methods
*********/
/// <summary>The method invoked when the game updates its state.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnUpdateTicked(object sender, EventArgs e)
{
if (this.LastEvent != null && Game1.CurrentEvent == null)
this.Monitor.Log($"Event {this.LastEvent.id} just ended!");
this.LastEvent = Game1.CurrentEvent;
}
}
自定义优先级
SMAPI calls event handlers in the same order they're registered by default, so the first event handler registered is the first to receive the event each time. This isn't always predictable, since it depends on mod load order and when each mod registers their handlers. This order is also an implementation detail, so it's not guaranteed.
If you need more control over the order, you can specify an event priority using the [EventPriority]
attribute: Low (after most handlers), Default, High (before most handlers), or a custom value (e.g., High + 1 is higher priority than High). You should only do this if strictly needed; depending on event handler order between mods is fragile (e.g., the other mod might change its priority too).
/// <summary>The main entry point for the mod.</summary>
public class ModEntry : Mod
{
/*********
** Public methods
*********/
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// <param name="helper">Provides simplified APIs for writing mods.</param>
public override void Entry(IModHelper helper)
{
helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked;
}
/*********
** Private methods
*********/
/// <summary>The method invoked when the game updates its state.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
[EventPriority(EventPriority.High)]
private void OnUpdateTicked(object sender, EventArgs e)
{
this.Monitor.Log("Update!");
}
}