「模组:创建 SMAPI 模组」修訂間的差異

出自Stardew Valley Wiki
跳至導覽 跳至搜尋
行 71: 行 71:
 
# 创建 类库 项目,选择 .NET Framework 框架 (参阅 [[模组:IDE 参考#创建项目|如何创建一个项目]])。确保你选择的是 .NET Framework 而不是 .NET Core 或者 .NET Standard
 
# 创建 类库 项目,选择 .NET Framework 框架 (参阅 [[模组:IDE 参考#创建项目|如何创建一个项目]])。确保你选择的是 .NET Framework 而不是 .NET Core 或者 .NET Standard
 
# 选择目标框架版本为 .NET Framework 4.5 或 4.5.1,使用 4.5.2 最佳 (参阅 [[模组:IDE 参考#选择目标框架|如何改变目标框架]])
 
# 选择目标框架版本为 .NET Framework 4.5 或 4.5.1,使用 4.5.2 最佳 (参阅 [[模组:IDE 参考#选择目标框架|如何改变目标框架]])
# 参考 [https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig <tt>Pathoschild.Stardew.ModBuildConfig</tt> NuGet 包 管理器] (参阅 [[模组:IDE 参考#添加 NuGet 包|如何添加 NuGet 包]]).
+
# 参考 [https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig <tt>Pathoschild.Stardew.ModBuildConfig</tt> NuGet 包] (参阅 [[模组:IDE 参考#添加 NuGet 包|如何添加 NuGet 包]]).
 
# 安装完包之后重新启动 Visual Studio 或者 MonoDevelop
 
# 安装完包之后重新启动 Visual Studio 或者 MonoDevelop
  

於 2021年4月12日 (一) 15:09 的修訂

製作SMAPI模組 SMAPI mascot.png


模組:目錄

Robin building.png
“我這裡還有很多事情需要處理。”
— 羅賓

不完整的翻譯

本文或部分尚未完全翻譯成中文。 歡迎您通過編輯幫助其建設。
最後編輯1059 Studio於2021-04-12 15:09:27.

要為遊戲創建 SMAPI 模組?教程就在這兒。要使用模組,請參閱 使用指南。要創建內容包模組,請參閱 模組:Content Patcher

介紹

什麼是 SMAPI 模組?

SMAPI 模組 使用改裝接口來擴展遊戲邏輯。可以在遊戲中發生某些情況時做出響應(例如,將對象放置在世界中),定期運行代碼(例如每個更新周期一次),更改遊戲的資源和數據等。SMAPI 模組使用 C# 編寫,使用 .NET Framework 和 Stardew Valley 將 XNA / MonoGame 用於遊戲邏輯(繪製到屏幕,用戶輸入等)。

為什麼模組使用 SMAPI?

SMAPI 可以做許多事情,例如:

  1. 將模組加載到遊戲中。沒有 SMAPI 就無法加載代碼模組。
  2. 提供接口和事件,能夠以其他方式與遊戲互動。有一些簡化的接口,可用於更改遊戲資源/數據,玩家配置,轉換,反映等。這些內容將在本指南的後面部分介紹。
  3. 在跨平台兼容時進行重構,這樣一來就不必擔心遊戲在 Linux/Mac/Windows 版本之間的差異。
  4. 重構模組以更新它。在常見情況下,SMAPI 會檢測並修復遊戲更新所破壞的模組代碼。
  5. 攔截錯誤。如果模組崩潰或發生錯誤,SMAPI 將攔截該錯誤,在控制台窗口中顯示錯誤詳細信息,並且在大多數情況下自動恢復遊戲。這意味着減少遊戲意外崩潰,並且可以更輕鬆地解決錯誤。
  6. 提供更新檢查。當有新版本可用時,SMAPI 會自動提醒玩家。
  7. 提供兼容性檢查。SMAPI 會自動檢測模組何時不兼容,並在它導致問題之前將其禁用,以防止遊戲爆炸。

我能製作一個模組嗎?

是的!本指南將幫助你逐步創建一個簡單的模組。然後你可以繼續學習,讓它做您想做的事即可。 如果你是編程新手,許多模組開發人員開始時幾乎沒有或完全沒有編程經驗。如果你下定決心,當然可以沿途學習,但是您應該為陡峭的學習曲線做好準備。剛開始時不要太過於自信,弄清楚它的時候,最好從一個小的模組開始。一開始很容易變得不知所措並放棄。模組社區非常熱情,所以不要害怕問問題!

如果你已經具備編程經驗,那應該沒問題。具有 C# 或 Java 的編程經驗將使事情變得容易,但這並不重要。如果不熟悉 C#,則可以瀏覽下面的「學習C#」參考資料以填補所有空白。

我可以不使用 SMAPI 來製作模組嗎?

當然。許多的 SMAPI 模組支持 內容包,可以讓你提供它們所使用的 JSON 文本文件、圖像等。例如,你可以 使用 Content Patcher 來編輯遊戲的貼圖並且不需要任何編程技術。本指南的其餘部分是關於創建新的 SMAPI 模組的。有關內容包,請參閱 模組:Content Patcher (或模組的文檔(如果為其他mod創建內容包)).

我在哪裡可以得到幫助?

星露谷模組社區歡迎你的到來. Feel free to ask for help in #making-mods on the Stardew Valley Discord.

開始

學習 C#

由於模組是用 C# 編寫的,因此最好先熟悉它。無需記住所有內容,但是掌握基礎知識(例如字段、方法、變量和類)將使其他所有內容都變得更加容易。

一些有用的資源:

要求

在你開始之前:

  1. 熟悉 玩家指南,本指南的其餘部分假定你已經熟悉使用模組。
  2. 安裝遊戲
  3. 安裝 SMAPI
  4. 安裝開發環境

如果你不熟悉 Visual Studio (on Windows/Mac) 或者 MonoDevelop (on Linux), 模組:IDE 參考 解釋了如何完成本指南所需的重要工作。

創建一個基礎的模組

快速開始

如果你有足夠的經驗來跳過本教程,則此部分的簡要概述如下:

快速開始 
  1. 創建一個空的 C#類庫 項目
  2. 目標框架選擇 .NET Framework 4.5 或者 4.5.1, 建議使用 4.5.2
  3. 參考 Pathoschild.Stardew.ModBuildConfig NuGet package 根據要在其上編譯模組的平台自動添加正確的引用。
  4. 創建一個 ModEntry 類,該類將 StardewModdingAPI.Mod 子類化
  5. 覆寫 Entry 方法,並使用 SMAPI events and APIs 編寫代碼
  6. 創建一個 manifest.json 文件 來描述了你的 SMAPI 模組
  7. 創建 一個包含模組文件的zip壓縮包 來發布

創建解決方案

一個 SMAPI 模組是具有 SMAPI 調用入口方法的動態鏈接庫(DLL),因此要對其進行設置

  1. 打開 Visual Studio 或者 MonoDevelop.
  2. 創建 類庫 項目,選擇 .NET Framework 框架 (參閱 如何創建一個項目)。確保你選擇的是 .NET Framework 而不是 .NET Core 或者 .NET Standard
  3. 選擇目標框架版本為 .NET Framework 4.5 或 4.5.1,使用 4.5.2 最佳 (參閱 如何改變目標框架)
  4. 參考 Pathoschild.Stardew.ModBuildConfig NuGet 包 (參閱 如何添加 NuGet 包).
  5. 安裝完包之後重新啟動 Visual Studio 或者 MonoDevelop

Add the code

Next let's add some code SMAPI will run.

  1. Delete the Class1.cs or MyClass.cs file (see how to delete a file).
  2. Add a C# class file called ModEntry.cs to your project (see how to add a file).
  3. Put this code in the file (replace YourProjectName with the name of your project):
    using System;
    using Microsoft.Xna.Framework;
    using StardewModdingAPI;
    using StardewModdingAPI.Events;
    using StardewModdingAPI.Utilities;
    using StardewValley;
    
    namespace YourProjectName
    {
        /// <summary>The mod entry point.</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.Input.ButtonPressed += this.OnButtonPressed;
            }
    
    
            /*********
            ** Private methods
            *********/
            /// <summary>Raised after the player presses a button on the keyboard, controller, or mouse.</summary>
            /// <param name="sender">The event sender.</param>
            /// <param name="e">The event data.</param>
            private void OnButtonPressed(object sender, ButtonPressedEventArgs e)
            {
                // ignore if player hasn't loaded a save yet
                if (!Context.IsWorldReady)
                    return;
    
                // print button presses to the console window
                this.Monitor.Log($"{Game1.player.Name} pressed {e.Button}.", LogLevel.Debug);
            }
        }
    }
    

Here's a breakdown of what that code is doing:

  1. using X; (see using directive) makes classes in that namespace available in your code.
  2. namespace YourProjectName (see namespace keyword) defines the scope for your mod code. Don't worry about this when you're starting out, Visual Studio or MonoDevelop will add it automatically when you add a file.
  3. public class ModEntry : Mod (see class keyword) creates your mod's main class, and subclasses SMAPI's Mod class. SMAPI will detect your Mod subclass automatically, and Mod gives you access to SMAPI's APIs.
  4. public override void Entry(IModHelper helper) is the method SMAPI will call when your mod is loaded into the game. The helper provides convenient access to many of SMAPI's APIs.
  5. helper.Events.Input.ButtonPressed += this.OnButtonPressed; adds an 'event handler' (i.e. a method to call) when the button-pressed event happens. In other words, when a button is pressed (the helper.Events.Input.ButtonPressed event), SMAPI will call your this.OnButtonPressed method. See events in the SMAPI reference for more info.

Add your manifest

The mod manifest tells SMAPI about your mod.

  1. Add a file named manifest.json to your project.
  2. Paste this code into the file:
    {
      "Name": "<your project name>",
      "Author": "<your name>",
      "Version": "1.0.0",
      "Description": "<One or two sentences about the mod>",
      "UniqueID": "<your name>.<your project name>",
      "EntryDll": "<your project name>.dll",
      "MinimumApiVersion": "3.0.0",
      "UpdateKeys": []
    }
    
  3. Replace the <...> placeholders with the correct info. Don't leave any <> symbols!

This will be listed in the console output when the game is launching. For more info, see the manifest docs.

Try your mod

  1. Build the project.
    If you did the create the project steps correctly, this will automatically add your mod to the game's Mods folder.
  2. Run the game through SMAPI.

The mod so far will just send a message to the console window whenever you press a key in the game.

Troubleshoot

If the tutorial mod doesn't work...

  1. Review the above steps to make sure you didn't skip something.
  2. Check for error messages which may explain why it's not working:
    • In Visual Studio, click Build > Rebuild Solution and check the Output pane or Error list.
    • In MonoDevelop, click Build > Rebuild All and wait until it's done. Then click the "Build: XX errors, XX warnings" bar at the top, and check the XX Errors and Build Output tabs.
  3. See the troubleshooting guide.
  4. If all else fails, come ask for help in the #modding in the Stardew Valley Discord. :)

FAQs

Where's the SMAPI documentation?

This is just the 'getting started' tutorial. For more documentation, see the SMAPI reference and the topics listed on the index page.

How do I make my mod work crossplatform?

SMAPI will automatically adjust your mod so it works on Linux, MacOS, and Windows. However, there are a few things you should do to avoid problems:

  1. Use the crossplatform build config package to automatically set up your project references. This makes crossplatform compatibility easier and lets your code compile on any platform. (If you followed the above guide, you already have this.)
  2. Use Path.Combine to build file paths, don't hardcode path separators since they won't work on all platforms.
    // ✘ Don't do this! It won't work on Linux/Mac.
    string path = this.Helper.DirectoryPath + "\assets\image.png";
    
    // ✓ This is OK
    string path = Path.Combine(this.Helper.DirectoryPath, "assets", "image.png");
    
  3. Use this.Helper.DirectoryPath, don't try to determine the mod path yourself.
    // ✘ Don't do this! It will crash if SMAPI rewrites the assembly (e.g. to update or crossplatform it).
    string modFolder = Assembly.GetCallingAssembly().Location;
    
    // ✓ This is OK
    string modFolder = this.Helper.DirectoryPath;
    

How do I decompile the game code?

It's often useful to see how the game code works. The game code is compiled into StardewValley.exe (i.e. converted to a machine-readable format), but you can decompile it get a mostly-readable approximation of the original code. (This might not be fully functional due to decompiler limitations, but you'll be able to see what it's doing.)

To decompile the game code...

On Windows:
  1. First-time setup:
    1. Install the latest ILSpy release (get the "ILSpy_binaries" file under assets).
    2. Open ILSpy.
    3. Click View > Options, scroll to the "Other" section at the bottom, and enable "Always qualify member references".
  2. Open StardewValley.exe in ILSpy.
  3. Right-click on Stardew Valley and choose Save Code to create a decompiled project you can open in Visual Studio.
On Linux/MacOS:
  1. Install Visual Studio Code.
  2. Get the ILSpy .NET Decompiler plugin for VSCode.
  3. Open the Visual Studio Code Command Palette (Command+Shift+P), then type ilspy to show the two commands.
  4. Choose Decompile IL Assembly (pick file), then choose the StardewValley.exe in your game folder.
  5. A tree view named ILSPY DECOMPILED MEMBERS should appear in the Explorer view. This lets you expand and select various nodes to see the decompiled C# code in the editor.

To unpack the XNB data/image files, see Modding:Editing XNB files.