Line 6: |
Line 6: |
| ==Basic techniques== | | ==Basic techniques== |
| ===Tracking changes to a value=== | | ===Tracking changes to a value=== |
− | Mods often need to know when a value changed. If there's no SMAPI event for the value, you can create a private [https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/fields field] to track the value, and update it using the update tick event. For example, here's a fully functional mod which prints a console message when the player's stamina changes: | + | Mods often need to know when a value changed. If there's no SMAPI event for the value, you can create a private [https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/fields field] to track the value, and update it using the update tick event. |
| | | |
− | <source lang="c#">
| + | See [[Modding:Modder Guide/APIs/Events#Change monitoring]] for an example. |
− | /// <summary>The mod entry point.</summary>
| |
− | internal class ModEntry : Mod
| |
− | {
| |
− | /********* Properties *********/
| |
− | /// <summary>The player's last stamina value.</summary>
| |
− | private float LastStamina;
| |
− | | |
− | /********* 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)
| |
− | {
| |
− | GameLoop.SaveLoaded += this.onSaveLoaded;
| |
− | GameLoop.UpdateTicked += this.onUpdateTicked;
| |
− | }
| |
− | | |
− | | |
− | /********* Private methods *********/
| |
− | /// <summary>The method invoked when the player loads a save.</summary>
| |
− | /// <param name="sender">The event sender.</param>
| |
− | /// <param name="e">The event arguments.</param>
| |
− | private void onSaveLoaded(object sender, SaveLoadedEventArgs e)
| |
− | {
| |
− | this.LastStamina = Game1.player.Stamina;
| |
− | }
| |
− | | |
− | /// <summary>The method invoked after the game updates (roughly 60 times per second).</summary>
| |
− | /// <param name="sender">The event sender.</param>
| |
− | /// <param name="e">The event arguments.</param>
| |
− | private void onUpdateTicked (object sender, UpdateTickedEventArgs e)
| |
− | {
| |
− | // skip if save not loaded yet
| |
− | if (!Context.IsWorldReady)
| |
− | return;
| |
− | | |
− | // skip if stamina not changed
| |
− | float currentStamina = Game1.player.Stamina;
| |
− | if (currentStamina == this.LastStamina)
| |
− | return;
| |
− | | |
− | // print message & update stamina
| |
− | this.Monitor.Log($"Player stamina changed from {currentStamina} to {this.LastStamina}", LogLevel.Debug);
| |
− | this.LastStamina = currentStamina;
| |
− | }
| |
− | }
| |
− | </source>
| |
| | | |
| ==Items== | | ==Items== |