“模组:创建 SMAPI 模组”的版本间的差异

来自Stardew Valley Wiki
跳到导航 跳到搜索
第65行: 第65行:
 
}}
 
}}
  
===Create the project===
+
=== 创建解决方案===
A SMAPI mod is a compiled library (DLL) with an entry method that gets called by SMAPI, so let's set that up.
+
一个 SMAPI 模组是具有 SMAPI 调用入口方法的动态链接库(DLL),因此要对其进行设置
  
# Open Visual Studio or MonoDevelop.
+
# 打开 Visual Studio 或者 MonoDevelop.
# Create a solution with a .NET Framework class library project (see [[Modding:IDE reference#create-project|how to create a project]]). '''Make sure you choose .NET Framework, not .NET Core or .NET Standard.'''
+
# 创建 类库 项目,选择 .NET Framework 框架 ( 参阅 [[ 模组:IDE 参考# 创建项目| 如何创建一个项目]]) 。确保你选择的是 .NET Framework 而不是 .NET Core 或者 .NET Standard
# Change the target framework to .NET Framework 4.5, 4.5.1, or 4.5.2 for best compatibility (see [[Modding:IDE reference#set-target-framework|how to change target framework]]).
+
# 选择目标框架版本为 .NET Framework 4.5 4.5.1 ,使用 4.5.2 最佳 ( 参阅 [[ 模组:IDE 参考# 选择目标框架| 如何改变目标框架]])
# Reference the [https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig <tt>Pathoschild.Stardew.ModBuildConfig</tt> NuGet package] (see [[Modding:IDE reference#add-nuget|how to add the package]]).
+
# 参考 [https://www.nuget.org/packages/Pathoschild.Stardew.ModBuildConfig <tt>Pathoschild.Stardew.ModBuildConfig</tt> NuGet 包管理器] ( 参阅 [[ 模组:IDE 参考# 添加 NuGet 包| 如何添加 NuGet 包]]).
# Restart Visual Studio/MonoDevelop after installing the package.
+
# 安装完包之后重新启动 Visual Studio 或者 MonoDevelop
  
 
===Add the code===
 
===Add the code===

2021年4月12日 (一) 15:08的版本

制作SMAPI模组 SMAPI mascot.png


模组:目录

Robin building.png
“我这里还有很多事情需要处理。”
— 罗宾

不完整的翻译

本文或部分尚未完全翻译成中文。 欢迎您通过编辑帮助其建设。
最后编辑1059 Studio于2021-04-12 15:08:43.

要为游戏创建 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.