Modding:Modder Guide/APIs/Events

From Stardew Valley Wiki
< Modding:Modder Guide‎ | APIs
Revision as of 04:09, 5 November 2018 by Pathoschild (talk | contribs) (→‎Multiplayer: + PeerDisconnected, update event)
Jump to navigation Jump to search

Creating SMAPI mods SMAPI mascot.png


Modding:Index

SMAPI provides several C# events which let your mod respond when something happens (like when the player places an object) or run code periodically (like once per update tick).

Intro

A C# event is the way that SMAPI notifies mods when something happens. You can add any number of event handlers (methods to call) when an event is raised. Event handlers are usually added in your Entry method, though you can add and remove them anytime.

For example, let's say you want to print a message when the player loads a save. First you would choose the appropriate event from the list below (SaveEvents.AfterLoad), then add an event handler, and do something in your method code:

/// <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)
    {
        // SaveEvents.AfterLoad is the event
        // this.SaveEvents_AfterLoad is the method below you want to call
        SaveEvents.AfterLoad += this.SaveEvents_AfterLoad;
    }

    /// <summary>The method called after the player loads their save.</summary>
    /// <param name="sender">The event sender.</param>
    /// <param name="e">The event arguments.</param>
    private void SaveEvents_AfterLoad(object sender, EventArgs e)
    {
       this.Monitor.Log("The player loaded their game! This is a good time to do things.");
       this.Monitor.Log("Everything in the world is ready to interact with at this point.");
    }
}

Tip: you don't need to memorise the method arguments. In Visual Studio, type SaveEvents.AfterLoad += and press TAB to auto-create a method. (There doesn't seem to be an equivalent feature in MonoDevelop.)

Events

The available events are documented below.

Content

ContentEvents are raised when the game loads content from its XNB files or changes locale.

event summary
AfterLocaleChanged Raised after the content language changes.

Control

ControlEvents are raised when the player uses a controller, keyboard, or mouse. They're raised before the game handles the input, so it's possible to selectively prevent the game from responding to it. (That's beyond the scope of this guide, but it involves overwriting Game1.oldKBState, Game1.oldMouseState, and Game1.oldPadState.)

Most of these events are split into two variants, XPressed and XReleased. The Pressed variant is raised when the player presses the button (holding the button down only triggers the event once), and the Released variant is raised when they release it.

Note: mods won't receive input sent to the chatbox, or the toggle-chatbox key.

event summary
ControllerButtonPressed
ControllerButtonReleased
Raised after the player pressed/released a button on a gamepad or controller. These events aren't raised for trigger buttons.
ControllerTriggerPressed
ControllerTriggerReleased
Raised after the player pressed/released a trigger button on a gamepad or controller.
KeyPressed
KeyReleased
Raised after the player pressed/released a keyboard key.
KeyboardChanged Raised after the game's KeyboardState changed. That happens when the player presses or releases a key.
MouseChanged Raised after the game's MouseState changed. That happens when the player moves the mouse, scrolls the mouse wheel, or presses/releases a button.

Game

GameEvents are raised when the game changes state.

event summary
FirstUpdateTick Raised after the game first updates its state. This happens once per game session (unrelated to loading saves).
UpdateTick Raised when the game updates its state (≈60 times per second).
SecondUpdateTick Raised every other tick (≈30 times per second).
FourthUpdateTick Raised every fourth tick (≈15 times per second).
EighthUpdateTick Raised every eighth tick (≈8 times per second).
QuarterSecondTick Raised every 15th tick (≈4 times per second).
HalfSecondTick Raised every 30th tick (≈twice per second).
OneSecondTick Raised every 60th tick (≈once per second).

Graphics

GraphicsEvents are raised during the game's draw loop, when the game is rendering content to the window.

event summary
OnPreRenderEvent
OnPostRenderEvent
Raised before and after drawing the world to the screen.
OnPreRenderGuiEvent
OnPostRenderGuiEvent
When a menu is open (Game1.activeClickableMenu != null), raised before and after drawing that menu to the screen. This includes the game's internal menus like the title screen.
OnPreRenderHudEvent
OnPostRenderHudEvent
Raised before and after drawing the HUD (item toolbar, clock, etc) to the screen. The HUD is available at this point, but not necessarily visible. (For example, the event is called even if a menu is open.)
Resize Raised after the game window is resized.

Input

InputEvents are raised when the player uses a controller, keyboard, or mouse.

Note: mods won't receive input sent to the chatbox, or the toggle-chatbox key.

event summary
ButtonPressed
ButtonReleased
Raised after the player pressed/released a keyboard, mouse, or controller button. The event arguments include:
  • the button pressed (as an SButton constant);
  • whether the input counts as a 'click' (including the controller equivalent);
  • the cursor position on the screen;
  • the tile under the cursor;
  • the 'grab tile' (i.e. the tile the game considers to be clicked).

You can also...

  • get the equivalent XNA button constants using button.TryGetKeyboard(…) and button.TryGetController(…);
  • prevent the game (but not other mods) from handling the input using eventArgs.SuppressButton().

Location

LocationEvents are raised when the player transitions between game locations, a location is added or removed, or the objects in the current location change.

event summary
LocationsChanged Raised after a game location is added or removed (including building interiors). Handlers are passed lists of added/removed locations.
BuildingsChanged Raised after buildings is added/removed in any location. Handlers are given the location, and lists of added/removed buildings.
ObjectsChanged Raised after objects are added/removed in any location (including building interiors). Handlers are given the location, and lists of added/removed objects.

Menu

MenuEvents are raised when a game menu is opened or closed (including internal menus like the title screen).

event summary
MenuChanged Raised after a game menu is opened or replaced with another menu. This event is not invoked when a menu is closed. Handlers are given the previous menu (if any) and new menu (if any).
MenuClosed Raised after a game menu is closed. Handlers are given the previous menu.

Mine

MineEvents are raised when something happens in The Mines.

event summary
MineLevelChanged Raised after the player warps to a new level of the mine. Handlers are passed the previous and new mine level as arguments.

Multiplayer

MultiplayerEvents are raised during the multiplayer sync process. These are specialised events; most mods shouldn't use these directly.

event summary
BeforeMainSync
AfterMainSync
Raised before and after the game fetches data from other players and syncs the world to match.
BeforeMainBroadcast
AfterMainBroadcast
Raised before/after the game sends world data to other players. This event is raised for the main world broadcast, but a few specialised broadcasts (particularly sprite broadcasts) occur outside this event.

Player

PlayerEvents are raised when the player data changes.

event summary
InventoryChanged Raised after the current player's inventory changes in any way (added or removed item, sorted, etc).
LeveledUp Raised after the current player levels up a skill. This happens as soon as they level up, not when the game notifies the player after their character goes to bed.
Warped Raised after the current player moves to a new location.

Save

SaveEvents are raised when the player saves or loads the game.

event summary
BeforeCreate
AfterCreate
Raised before and 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.
AfterLoad Raised after the player loads a saved game (or starts a new save). The world is ready for mods to modify at this point.
BeforeSave
AfterSave
Raised before and after the game updates the save file. Not raised for the initial creation. The save won't be written until all mods have finished handling this event.
AfterReturnToTitle Raised after the player exits to the title screen.

Time

TimeEvents are raised when the in-game date or time changes.

event summary
AfterDayStarted Raised after the game begins a new day, including when loading a save.
TimeOfDayChanged Raised after the in-game clock changes.

Specialised

SpecialisedEvents serve specialised edge cases and should not be used by most mods. Mods using specialised events will be flagged in the SMAPI console as potentially impacting the game stability.

expand for details 
event summary
UnvalidatedUpdateTick Raised 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.

Events (SMAPI 3.0)

The following describes the upcoming SMAPI 3.0, and may change before release.

SMAPI 3.0 will introduce a new event system that's much more powerful, flexible, and consistent. You can try these events now, but these are preview prototypes and may change at any time. See Modding:Migrate to SMAPI 3.0 for details.

Display

this.Helper.Events.Displays has events linked to UI and drawing to the screen.

event summary
#MenuChanged Raised after a game menu is opened, closed, or replaced.

Event arguments:

event arg type description
e.NewMenu IClickableMenu The new menu instance (or null if none).
e.OldMenu IClickableMenu The old menu instance (or null if none).
#Rendering Raised before the game draws anything to the screen in a draw tick, as soon as the sprite batch is opened. The sprite batch may be closed and reopened multiple times after this event is called, but it's only raised once per draw tick. This event isn't useful for drawing to the screen, since the game will draw over it.

Limitations:

  • The event isn't raised during some cutscenes or minigames (e.g. the board game scene) due to limitations in the game design.

Event arguments:

event arg type description
e.SpriteBatch SpriteBatch The sprite batch being drawn. Add anything you want to appear on-screen to this sprite batch.
#Rendered Raised after the game draws to the sprite patch in a draw tick, just before the final sprite batch is rendered to the screen. Since the game may open/close the sprite batch multiple times in a draw tick, the sprite batch may not contain everything being drawn and some things may already be rendered to the screen. Content drawn to the sprite batch at this point will be drawn over all vanilla content (including menus, HUD, and cursor).

Limitations:

  • The event isn't raised during some cutscenes or minigames (e.g. the board game scene) due to limitations in the game design.

Event arguments:

event arg type description
e.SpriteBatch SpriteBatch The sprite batch being drawn. Add anything you want to appear on-screen to this sprite batch.
#RenderingWorld Raised before the game world is drawn to the screen. This event isn't useful for drawing to the screen, since the game will draw over it.

Event arguments:

event arg type description
e.SpriteBatch SpriteBatch The sprite batch being drawn. Add anything you want to appear on-screen to this sprite batch.
#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.

Event arguments:

event arg type description
e.SpriteBatch SpriteBatch The sprite batch being drawn. Add anything you want to appear on-screen to this sprite batch.
#RenderingActiveMenu When a menu is open (Game1.activeClickableMenu != null), raised before that menu is drawn to the screen. This includes the game's internal menus like the title screen. Content drawn to the sprite batch at this point will appear under the menu.

Event arguments:

event arg type description
e.SpriteBatch SpriteBatch The sprite batch being drawn. Add anything you want to appear on-screen to this sprite batch.
#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.

Event arguments:

event arg type description
e.SpriteBatch SpriteBatch The sprite batch being drawn. Add anything you want to appear on-screen to this sprite batch.
#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.

Event arguments:

event arg type description
e.SpriteBatch SpriteBatch The sprite batch being drawn. Add anything you want to appear on-screen to this sprite batch.
#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.

Event arguments:

event arg type description
e.SpriteBatch SpriteBatch The sprite batch being drawn. Add anything you want to appear on-screen to this sprite batch.
#WindowResized Raised after the game window is resized.

Event arguments:

event arg type description
e.OldSize Point The previous window width (e.OldSize.X) and height (e.OldSize.Y).
e.NewSize Point The new window width (e.NewSize.X) and height (e.NewSize.Y).

Game loop

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
Raised before/after the game state is updated (≈60 times per second).

Event arguments:

event arg type description
e.Ticks int The number of ticks elapsed since the game started, including the current tick.
e.IsOneSecond bool Whether e.TicksElapsed is a multiple of 60, which happens approximately once per second.
e.IsMultipleOf(int number) method returns bool Whether e.TicksElapsed is a multiple of the given number. This is mainly useful if you want to run logic intermittently (e.g. e.IsMultipleOf(30) for every half-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.
#SaveLoaded Raised before/after the game reads data from a save file and initialises the world. 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. 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.

Event arguments:

event arg type description
e.OldTime int The previous time of day in 24-hour notation (like 1600 for 4pm). The clock time resets when the player sleeps, so 2am (before sleeping) is 2600.
e.NewTime int The current time of day in 24-hour notation (like 1600 for 4pm). The clock time resets when the player sleeps, so 2am (before sleeping) is 2600.
#ReturnedToTitle Raised after the game returns to the title screen.

Input

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
#ButtonPressed
ButtonReleased
Raised after the player pressed/released a keyboard, mouse, or controller button. This includes mouse clicks.

Event arguments:

event arg type description
e.Button SButton The button pressed or released.
e.Cursor ICursorPosition The cursor position and grab tile.
e.IsDown method returns bool Indicates whether a given button is currently pressed.
e.IsSuppressed method returns bool A method which indicates whether a given button was suppressed by a mod, so the game itself won't see it. Note: mods won't receive input sent to the chatbox.
#CursorMoved Raised after the player moves the in-game cursor.

Event arguments:

event arg type description
e.OldPosition ICursorPosition The previous cursor position and grab tile.
e.NewPosition ICursorPosition The current cursor position and grab tile.
#MouseWheelScrolled Raised after the player scrolls the mouse wheel.

Event arguments:

event arg type description
e.Position ICursorPosition The current cursor position and grab tile.
e.Delta int The amount by which the mouse wheel was scrolled since the last update.
e.OldValue
e.NewValue
int The previous and current scroll value, cumulative since the game started. Mods should generally use e.Delta instead.

Multiplayer

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. This happens before the game approves the connection, so the player does not yet exist in the game. This is the earliest point where messages can be sent to the player via SMAPI.

Event arguments:

event arg type description
e.Peer IMultiplayerPeer The peer whose context was received (see Multiplayer#Get connected player info).
#ModMessageReceived Raised after a mod message is received over the network.

Event arguments:

event arg type description
e.FromPlayerID long The unique ID of the player from whose computer the message was sent.
e.FromModID string The unique ID of the mod which sent the message.
e.Type string A message type which you can use to decide whether it's the one you want to handle. This isn't necessarily globally unique, so you should also check the FromModID field.
e.ReadAs<TModel>() method returns TModel Read the underlying message data into the given model type (like e.ReadAs<MyMessageClass>() or e.ReadAs<string>()). This will return a new instance each time.
#PeerDisconnected Raised after the connection to a player is severed.

Event arguments:

event arg type description
e.Peer IMultiplayerPeer The peer whose connection was severed (see Multiplayer#Get connected player info).

Player

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.Player, e.Player.IsLocalPlayer, or e.Player.IsMainPlayer if needed.

event summary
#InventoryChanged Raised after items are added or removed from the player inventory.

Event arguments:

event arg type description
e.Player Farmer The player whose inventory changed.
e.Added IEnumerable<Item> The added item stacks.
e.Removed IEnumerable<Item> The removed item stacks.
e.StackSizeChanged IEnumerable<ItemStackSizeChange> The item stacks whose quantity changed. Each ItemStackSizeChange instance includes Item (the affected item stack), OldSize (the previous stack size), and NewSize (the new stack size).
#LevelChanged Raised after a player's skill level changes. When the player levels up normally, this is raised immediately (not when the game notifies the player after they go to bed).

Event arguments:

event arg type description
e.Player Farmer The player whose skill level changed.
Skill SkillType The skill whose level changed. This is a constant like SkillType.Combat, which can be converted to the game's internal skill ID using (int)e.Skill.
OldLevel int The player's previous level for that skill.
NewLevel int The player's new level for that skill.
#Warped Raised after the current player moves to a new location.

Event arguments:

event arg type description
e.Player Farmer The player who warped to a new location.
OldLocation GameLocation The player's previous location.
NewLocation GameLocation The player's new location.

World

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).

Event arguments:

event arg type description
e.Added IEnumerable<GameLocation> A list of locations added since the last update tick.
e.Removed IEnumerable<GameLocation> A list of locations removed since the last update tick.
#BuildingListChanged Raised after buildings are added/removed in any location.

Event arguments:

event arg type description
e.Location GameLocation The location which changed.
e.Added IEnumerable<Building> A list of buildings added since the last update tick.
e.Removed IEnumerable<Building> A list of buildings removed since the last update tick.
#DebrisListChanged Raised after debris is added/removed in any location (including dropped or spawned floating items).

Event arguments:

event arg type description
e.Location GameLocation The location which changed.
e.Added IEnumerable<Debris> A list of debris added since the last update tick.
e.Removed IEnumerable<Debris> A list of debris removed since the last update tick.
#LargeTerrainFeatureListChanged Raised after large terrain features (like bushes) are added/removed in any location.

Event arguments:

event arg type description
e.Location GameLocation The location which changed.
e.Added IEnumerable<LargeTerrainFeature> A list of large terrain features added since the last update tick.
e.Removed IEnumerable<LargeTerrainFeature> A list of large terrain features removed since the last update tick.
#NpcListChanged Raised after NPCs are added/removed in any location (including villagers, horses, Junimos, monsters, and pets).

Event arguments:

event arg type description
e.Location GameLocation The location which changed.
e.Added IEnumerable<NPC> A list of NPCs added since the last update tick.
e.Removed IEnumerable<NPC> A list of NPCs removed since the last update tick.
#ObjectListChanged Raised after objects are added/removed in any location (including machines, furniture, fences, etc). For floating items, see DebrisListChanged.

Event arguments:

event arg type description
e.Location GameLocation The location which changed.
e.Added IEnumerable<KeyValuePair<Vector2, Object>> A list of tile coordinate + object pairs added since the last update tick.
e.Removed IEnumerable<KeyValuePair<Vector2, Object>> A list of tile coordinate + object pairs removed since the last update tick.
#TerrainFeatureListChanged Raised after terrain features are added/removed in any location (including trees, hoed dirt, and flooring). For bushes, see LargeTerrainFeatureListChanged.

Event arguments:

event arg type description
e.Location GameLocation The location which changed.
e.Added IEnumerable<KeyValuePair<Vector2, TerrainFeature>> A list of tile coordinate + terrain feature pairs added since the last update tick.
e.Removed IEnumerable<KeyValuePair<Vector2, TerrainFeature>> A list of tile coordinate + terrain feature pairs removed since the last update tick.

Specialised

this.Helper.Events.Specialised has events for specialised edge cases. These shouldn't be used by most mods.

event summary
#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.

Event arguments:

event arg type description
e.Ticks int The number of ticks elapsed since the game started, including the current tick.
e.IsOneSecond bool Whether e.TicksElapsed is a multiple of 60, which happens approximately once per second.
e.IsMultipleOf(int number) method returns bool Whether e.TicksElapsed is a multiple of the given number. This is mainly useful if you want to run logic intermittently (e.g. e.IsMultipleOf(30) for every half-second).