Modding:Common tasks

Index

Axe.png
Article Stub

This article is marked as a stub for the following reason:

  • Missing information
  • Requires more formal, objective language cleanup

This page covers how to do common tasks in SMAPI mods. Before reading this page, see the Modder Guide and Game Fundamentals.

Basic techniques

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 field to track the value, and update it using the update tick event.

See Modding:Modder Guide/APIs/Events#Change monitoring for an example.

Items

Items are objects which represent things which can be put in an inventory. Tools, Crops, etc.

Create an item (Object)

All constructors for Object:

 public Object(Vector2 tileLocation, int parentSheetIndex, int initialStack);
 public Object(Vector2 tileLocation, int parentSheetIndex, bool isRecipe = false);
 public Object(int parentSheetIndex, int initialStack, bool isRecipe = false, int price = -1, int quality = 0);
 public Object(Vector2 tileLocation, int parentSheetIndex, string Givenname, bool canBeSetDown, bool canBeGrabbed, bool isHoedirt, bool isSpawnedObject);

Where parentSheetIndex is the ID of the item (can be found in ObjectInformation.xnb).

Spawn an item on the ground

You can spawn an item on the ground with the GameLocation class's dropObject method:

 public virtual bool dropObject(Object obj, Vector2 dropLocation, xTile.Dimensions.Rectangle viewport, bool initialPlacement, Farmer who = null);

 // Concrete code for spawning:
 Game1.getLocationFromName("Farm").dropObject(new StardewValley.Object(itemId, 1, false, -1, 0), new Vector2(x, y) * 64f, Game1.viewport, true, (Farmer)null);

Add an item to an inventory

//You can add items found in ObjectInformation using:
    Game1.player.addItemByMenuIfNecessary((Item)new StardewValley.Object(int parentSheetIndex, int initialStack, [bool isRecipe = false], [int price = -1], [int quality = 0]));

Another example:

    // Add a weapon directly into player's inventory
    const int WEAP_ID = 19;                  // Shadow Dagger -- see Data/weapons
    Item weapon = new MeleeWeapon(WEAP_ID);  // MeleeWeapon is a class in StardewValley.Tools
    Game1.player.addItemByMenuIfNecessary(weapon);

    // Note: This code WORKS.

Remove an item from an inventory

This is dependent on the inventory - rarely will you be calling this directly, as the game has functions for this for the Player, located in Farmer (in the main namespace).

To do so, in most situations, just call .removeItemFromInventory(Item)

Locations

See Game Fundamentals#GameLocation.

Get all locations

The list of root locations is stored in Game1.locations, but constructed building interiors aren't included. Instead, use the method Utility.ForAllLocations

Utility.ForAllLocations((GameLocation location) =>
{
   // do things with location here.
});

Note that farmhands in multiplayer can't see all locations; see GetActiveLocations instead.

Edit a location map

See Modding:Maps.

Position

A Character's position indicates the Character's coordinates in the current location.

Position Relative to the Map

Each location has an ``xTile`` map where the top-left corner of the map is (0, 0) and the bottom-right corner of the map is (location.Map.DisplayWidth, location.Map.DisplayHeight) in pixels.

There are two ways to get a Character's position in the current location: by absolute position and by tile position.

Position.X and Position.Y will give the XY coordinates in pixels.

getTileX() and getTileY() will give the XY coordinates in tiles.

Each tile is 64x64 pixels as specified by Game1.tileSize. The conversion between absolute and tile is as follows:

// Absolute position => Tile position
Math.Floor(Game1.player.Position.X / Game1.tileSize)
Math.Floor(Game1.player.Position.Y / Game1.tileSize)

// Tile position => Absolute position
Game1.player.getTileX() * Game1.tileSize
Game1.player.getTileY() * Game1.tileSize

// Tilemap dimensions
Math.Floor(Game1.player.currentLocation.Map.DisplayWidth / Game1.tileSize)
Math.Floor(Game1.player.currentLocation.Map.DisplayHeight / Game1.tileSize)

Position Relative to the Viewport

The viewport represents the visible area on the screen. Its dimensions are Game1.viewport.Width by Game1.viewport.Height in pixels; this is the same as the game's screen resolution.

The viewport also has an absolute position relative to the map, where the top-left corner of the viewport is at (Game1.viewport.X, Game1.viewport.Y).


The player's position in pixels relative to the viewport is as follows:

Game1.player.Position.X - Game1.viewport.X
Game1.player.Position.Y - Game1.viewport.Y

NPC

Creating Custom NPCs

Adding new NPCs involves editing a number of files:

All of the above can be done with an AssetRequested event or Content Patcher. If you did all of this correctly, the game will spawn the NPC in for you. (If you didn't, it swallows the error)

User-interface (UI)

The User-interface (UI) is a collection of separate elements which make up the HUD and occasional popups.

//TODO: This section needs to be expanded. Please contribute if you have knowledge in this area.

HUDMessage are those popups in the lower left hand screen. They have several constructors, which we will briefly go over here (a few non-relevant constructors are not included):

  public HUDMessage(string message);
  public HUDMessage(string message, int whatType);
  public HUDMessage(string type, int number, bool add, Color color, Item messageSubject = null);
  public HUDMessage(string message, string leaveMeNull)
  public HUDMessage(string message, Color color, float timeLeft, bool fadeIn)


So before we go over when you'd use them, I'm going to briefly note how the class HUDMessage uses these. (I encourage people to read the class if they have further questions, but I doubt most of us will need to know more than this)


 
All of the types for HUDMessage as they appear in-game.

Types available:

  1. Achievement (HUDMessage.achievement_type)
  2. New Quest (HUDMessage.newQuest_type)
  3. Error (HUDMessage.error_type)
  4. Stamina (HUDMessage.stamina_type)
  5. Health (HUDMessage.health_type)


Color: Fairly obvious. It should be noted that while the first two don't give an option (they default to Color:OrangeRed), the fourth with the param 'leaveMeNull' displays as the same color as the game text.


For specifics:

  • public HUDMessage(string type, int number, bool add, Color color, Item messageSubject = null); - This allows for expanded customization of the message. More often used for money.
  • public HUDMessage(string message, string leaveMeNull) - Also displays no icon.
Not only displaying no icon, this type of HUDMessage does not have the square on the left side; it will draw a simple rectangle with text within.
  • public HUDMessage(string message, Color color, float timeLeft, bool fadeIn) - Displays a message that fades in for a set amount of time.


Note: For those of you who want a custom HUDMessage: - Almost all of these variables are public, excluding messageSubject, so feel free to customize! To modify them make a HUDMessage variable like so : HUDMessage <name> = new HUDMessage(<message>) ,now you can even animate them with code!

For example: add a new HUDMessage to show   toaster popup.

Game1.addHUDMessage(new HUDMessage("MESSAGE", 3));

Another example: add a HUDMessage that shows up like a simple rectangle with no icon, and no square for the icon:

Game1.addHUDMessage(new HUDMessage("MESSAGE", ""));  // second parameter is the 'leaveMeNull' parameter

Active clickable menu

An active clickable menu is a UI drawn over everything else which accepts user input. For example, the game menu (shown in-game when you hit ESC or controller B) is an active clickable menu. The menu is stored in Game1.activeClickableMenu; if that field has a non-null value, the menu will be drawn and receive input automatically.

Each menu is different, so you need to look at the menu code to know how to interact with it. Since mods often need to get the current tab on the game menu, here's an example which handles the map tab:

if (Game1.activeClickableMenu is GameMenu menu)
{
  // get the tab pages
  IList<IClickableMenu> pages = this.Helper.Reflection.GetField<List<IClickableMenu>>(menu, "pages").GetValue();

  // option A: check tab ID
  if (menu.currentTab == GameMenu.mapTab)
  {
     ...
  }

  // option B: check page type
  switch (pages[menu.currentTab])
  {
    case MapPage mapPage:
       ...
       break;
  }
}

To create a custom menu, you need to create a subclass of IClickableMenu and assign it to Game1.activeClickableMenu. At its most basic, a menu is basically just a few methods you override (usually draw and receiveLeftClick at a minimum). When draw is called, you draw whatever you want to the screen; when receiveLeftClick is called, you check if it's within one of the clickable areas and handle it. Normally you'd use some convenience classes like ClickableTextureButton (which has a texture and position, and simplifies checking if they were clicked), though that's not strictly necessary. Here's a simple menu you can use as an example, which draws the birthday menu for Birthday Mod.

DialogueBox

 
Example of DialogueBox without choices.

A DialogueBox is a text box with a slightly larger, slightly boldfaced text, with "typewriter-like" effect.

There are several variants, including ones with a dialogue/conversation choices.

Within the message, use a caret "^" to put a linebreak.

Here is an example of a simple, choiceless output:

using StardewValley.Menus;  // This is where the DialogueBox class lives

string message = "This looks like a typewriter ... ^But it's not ...^It's a computer.^";
Game1.activeClickableMenu = new DialogueBox(message);

// TODO: More examples with choices

To utilise options, you are better off using createQuestionDialogue.

private void SampleClick()
{
    // List of choices to give the farmer.
    List<Response> choices = new List<Response>()
            {
                new Response("dialogue_id1","Choice 1" ),
                new Response("dialogue_id2", "Choice 2"),
                new Response("dialogue_id3", "Choice 3"),
                new Response("dialogue_id4", "Choice 4")
            };

    // And here we case it to pop up on the farmer's screen. When the farmer has picked a choice, it sends that information to the method below (DialogueSet
    Game1.currentLocation.createQuestionDialogue($"What is the question?", choices.ToArray(), new GameLocation.afterQuestionBehavior(DialogueSet));
}

public void DialogueSet(Farmer who, string dialogue_id)
{
	// Here you get which option was picked as dialogue_id.
	Game1.addHUDMessage(new HUDMessage($"Farmer {who} chose option {dialogue_id}"));
    
}

Mail

If you are new to SMAPI or to modding Stardew Valley in general, sending a simple letter to the player's mailbox is a great place to start your learning journey. You will be treated to some simple to understand code and concepts, as well as receive some instant gratification in the form of a tangible, in-game letter that you can see in action. If the examples in this section fall short, there are many folks available to assist you on the Discord channel (//TODO: Provide link).

Mail content

Before you can actually send any of your own custom mail to the player, you must decided how your letter will be composed. By that I mean, is your letter static - always the same text - or is it dynamic - text changes based on a variable piece of information? Obviously a static letter will be easier to implement, so if you are just starting off, go that route for now. However, both static and dynamic methods are explained below.

To send mail, whether static or dynamic, you first have to let Stardew Valley know about your content, also referred to as an asset. In the case of mail, you have to inject your additions into the mail data. You accomplish this via the IAssetEditor interface. You can implement IAssetEditor from your ModEntry class, or create a separate class that implements IAssetEditor to inject new mail content into "Data\Mail.xnb". The examples cited below use the latter approach for clarity, easy of reuse, and encapsulation:

Inject static content

Most times a static, predefined letter will suffice, whether you are including an attachment (i.e., object, money, etc.) or not. "Static" simply means you do not need to change the text once it is typed before sending the letter. A "static" letter will always be available in the game (unless you remove it from the mod or the mod is removed by the player) so that means the letter is still available if the player quits with your letter still in the mailbox and then returns to play later. This can be an issue with "dynamic" letters, as explained in more detail in that section, so use "static" content whenever possible.

You can softly reference the player's name, using "@", but other replace codes that may work in dialog texts, like %pet or %farm, do not work in static mail content at this time. However, you can make use of some special characters that display an icon in the letter, such as "=", which will display a purple star, "<", which will display a pink heart, the "$", which will be replaced with a gold coin, the ">", which will display a right arrow, the "`", which will display an up arrow, and the "+", which will display a head riding a skateboard (maybe?). There may be additional special cases as well that are not yet documented.

The example below adds 4 letters into the mail data collection. Note, that the code below does not send any letters to the player, but simply makes them available to Stardew Valley game so they can be sent.

using StardewModdingAPI;

namespace MyMod
{
    internal sealed class ModEntry: Mod
    {
        public override void Entry(IModHelper helper)
        {
            helper.Events.Content.AssetRequested += this.OnAssetRequested;
        }
        
        private void OnAssetRequested(object? sender, AssetRequestedEventArgs e)
        {
            if (e.NameWithoutLocale.IsEquivalentTo("Data/mail"))
            {
                e.Edit(this.EditImpl);
            }
        }

        public void EditImpl(IAssetData asset)
        {
            var data = asset.AsDictionary<string, string>().Data;

            // "MyModMail1" is referred to as the mail Id.  It is how you will uniquely identify and reference your mail.
            // The @ will be replaced with the player's name.  Other items do not seem to work (''i.e.,'' %pet or %farm)
            // %item object 388 50 %%   - this adds 50 pieces of wood when added to the end of a letter.
            // %item tools Axe Hoe %%   - this adds tools; may list any of Axe, Hoe, Can, Scythe, and Pickaxe
            // %item money 250 601  %%  - this sends a random amount of gold from 250 to 601 inclusive.
            // For more details, see: https://stardewvalleywiki.com/Modding:Mail_data 
            data["MyModMail1"] = "Hello @... ^A single carat is a new line ^^Two carats will double space.";
            data["MyModMail2"] = "This is how you send an existing item via email! %item object 388 50 %%";
            data["MyModMail3"] = "Coin $   Star =   Heart <   Dude +  Right Arrow >   Up Arrow `";
            data["MyWizardMail"] = "Include Wizard in the mail Id to use the special background on a letter";
        }
    }
}

Send a letter (using static content)

Now that you have your letter loaded, it's time to send it to the player. There are a couple different methods available to accomplish this as well, depending on your need. Two examples are shown below. The distinction between the two methods will be explained below:

    Game1.player.mailbox.Add("MyModMail1");
    Game1.addMailForTomorrow("MyModMail2");

The first method (Game1.player.mailbox.Add) adds the letter directly into the mailbox for the current day. This can be accomplished in your "DayStarting" event code, for example. Mail added directly to the mailbox is not "remembered" as being sent even after a save. This is useful in some scenarios depending on your need.

The second method (Game1.addMailForTomorrow) will, as the name implies, add the letter to the player's mailbox on the next day. This method remembers the mail (Id) sent making it possible not to send the same letter over and over. This can be handled in "DayStaring", "DayEnding" or other events, as dictated by your need.

You may be able to put the letter directly into the mailbox and also have it be remembered using the mailRecieved collection. You can simply add your mailId manually if you want it to be remembered when using the add directly to mailbox method.

If you want Stardew Valley to forget that a specific letter has already been sent, you can remove it from the mailReceived collection. You can iterate through the collection as well using a foreach should you need to remove mail en mass.

    Game1.player.mailReceived.Remove("MyModMail1");

That is all there is to sending a simple letter. Attaching objects and sending money via letter is straight-forward, but sending recipes is more complicated and will need some additional explanation at a future time.

Inject dynamic content

If you want to send a letter that contains data that needs to change based on the situation, such as the number of purple mushrooms eaten today, then you have to create that letter content each time you plan on sending it, especially if you want an up-to-date value. That is what I am referring to by "dynamic" letters.

Consider the following source code, which is basically an enhanced version of the static mail class shown above, that will also support "dynamic" content. You could certainly always use the enhanced version of this code and just not make use of the dynamic content unless needed. The code was separated for the purpose of illustrating the differences.

using StardewModdingAPI;
using System.Collections.Generic;

namespace MyMail
{
    internal sealed class ModEntry: Mod
    {
        // This collection holds any letters loaded after the initial load or last cache refresh
        private Dictionary<string, string> dynamicMail = new();
       
        public override void Entry(IModHelper helper)
        {
            helper.Events.Content.AssetRequested += this.OnAssetRequested;
        }

        private void OnAssetRequested(object? sender, AssetRequestedEventArgs e)
        {
             if (e.NameWithoutLocale.IsEquivalentTo("Data/mail"))
                 e.Edit(this.EditImpl);
        }

        public void EditImpl(IAssetData asset)
        {
            var data = asset.AsDictionary<string, string>().Data;

            // This is just an example
            data["StaticMail"] = "If there were any letters with static content they could be placed here.";

            // Inject any mail that was added after the initial load.
            foreach (var item in dynamicMail)
            {
                data.Add(item);
            }

            dynamicMail.Clear();    // For the usage of this MOD the letters are cleared
        }

        /// <summary>
        /// Add a new mail asset into the collection so it can be injected by the next cache refresh.  The letter will
        /// not be available to send until the cache is invalidated in the code.
        /// </summary>
        /// <param name="mailId">The mail key</param>
        /// <param name="mailText">The mail text</param>
        public void Add(string mailId, string mailText)
        {
            if (!string.IsNullOrEmpty(mailId))
            {
                dynamicMail[mailId] = mailText;
            }
        }
    }
}

You will notice that there is really very little difference in the code used for static mail and dynamic mail. The class that supports dynamic mail has a private dictionary collection for holding on to any mail content waiting to be injected. It could have been made public to allow mail to be added directly into the collection, but that is not good practice. Instead a public Add method was provided so that mail could be sent, so to speak, to the collection. This code is for a specific MOD, not a robust framework, so it isn't overly concerned with error handling. You can improve that based on your needs.

Notice the additional code in the Edit method, where any mail in the dynamicMail collection is injected into Stardew Valley's content. There will be no mail in the dynamicMail collection when the MOD is loaded (in this case) the first time. If you add mail after the original load, then the content will have to be reloaded by invalidating the cache. Refer to Cache invalidation for more details.

Send a letter (using dynamic content)

You can hook into other events, such as "Day Starting" or "Day Ending" to generate the letter you want to send. Consider this simple example, that is only for illustration purposes.

    private void OnDayStarting(object sender, DayStartedEventArgs e)
    {
        string mailMessage = $"@, you have gathered {Game1.stats.rabbitWoolProduced} units of rabbit wool!";

        mailData.Add("MyModMailWool", mailMessage);      // Add this new letter to the mail collection (for next refresh).

        Game1.mailbox.Add("MyModMailWool");              // Add to mailbox and we don't need to track it

        this.Helper.GameContent.InvalidateCache("Data\\mail"); // note that as of SMAPI 3.14.0, this only invalidates the English version of the asset. 
    }

This example formats a letter, showing the up-to-date count of rabbit wool, makes it available to the mail collection, places that letter in the mailbox, and then invalidates the cache so that this new letter will be injected during the cache refresh. In this case there is no need to remember mailId as the letter will be recreated each time it needs to be sent, which in this example is everyday. Again, this code is only for illustration of the concept.

There is an important caveat to understand when injecting mail in this simple fashion. The various mail frameworks available handle this issue, and this section will be expanded to explain how to overcome the issue, but it is being covered here to ensure you have a complete understanding of how MODs work with Stardew Valley and SMAPI.

If you add a dynamic letter and inject it into the content at Day Ending, you have to add the mail for display tomorrow obviously. That means the game will be saved with a reference to the dynamic letter ("MyMailModWool" in this example) pending in the mail box. If the player quits the game at that point and returns later to continue playing, then that dynamic letter is not available, resulting in a "phantom letter". The mailbox will show a letter is available but when clicked on nothing will display. This can be handled in several ways, including by saving the custom letters and loading them when the player continues, but again this example code does not cover that yet. That is why the example uses On Day Starting and makes the letter available right away.

Other

Add a small animation

location.temporarySprites.Add(new TemporaryAnimatedSprite(...))

See TemporaryAnimatedSprite for more details

Play a sound

location.playSound("SOUND");

(e.g., "junimoMeep1")

Open source

When all else fails, when you've looked at the decompiled source too long and it makes no sense, take a look at some open-source mod code! See the 'source' column in the mod compatibility list for source code.