前言
在这里就不一一介绍SMAPI的安装使用以及简单的mod项目搭建了,现在直接开始针对于N网优秀的mod源码进行解析,会长期慢慢更新内容
一、全局事件
1.日志打印
在Mod入口类中 Entry
方法加入全局日志函数
public override void Entry(IModHelper helper)
{
// 设置全局日志函数
Utils.InitLog(this.Monitor);
// 初始化I18n多语言文本
I18n.Init(helper.Translation);
...
}
方法中调用,打印信息至SMAPI控制台
string text = 'X';
// 打印内容
Utils.DebugLog($"Info {
text}.", LogLevel.Info);
下面是日志工具类,一个打印内容的方法,一个初始化方法
internal class Utils
{
/*********
** Properties
*********/
private static IMonitor MonitorRef;
/*********
** Public methods
*********/
public static void InitLog(IMonitor monitor)
{
Utils.MonitorRef = monitor;
}
public static void DebugLog(string message, LogLevel level = LogLevel.Trace)
{
#if WITH_LOGGING
Debug.Assert(Utils.MonitorRef != null, "Monitor ref is not set.");
Utils.MonitorRef.Log(message, level);
#else
if (level > LogLevel.Debug)
{
Debug.Assert(MonitorRef != null, "Monitor ref is not set.");
MonitorRef.Log(message, level);
}
#endif
}
public static bool Ensure(bool condition, string message)
{
#if DEBUG
if (!condition)
{
DebugLog($"Failed Ensure: {
message}");
}
#endif
return !!condition;
}
}
2.I18n
多语言切换,下面是简单的默认 en英文
json数据与 zh简中
json数据
default.json
{
"labels.single-price": "Single",
"labels.stack-price": "Stack"
}
zh.json
{
"labels.single-price": "单价",
"labels.stack-price": "总计"
}
I18n工具类,可直接调用方法获取对应语言翻译后的文本内容
internal static class I18n
{
/*********
** Fields
*********/
/// <summary>Mod翻译助手</summary>
private static ITranslationHelper Translations;
/*********
** Public methods
*********/
/// <summary>初始化</summary>
/// <param name="translations">Mod翻译助手</param>
public static void Init(ITranslationHelper translations)
{
I18n.Translations = translations;
}
/// <summary>获取单价对应翻译后的文本</summary>
public static string Labels_SinglePrice()
{
return I18n.GetByKey("labels.single-price");
}
/// <summary>获取总价对应翻译后的文本</summary>
public static string Labels_StackPrice()
{
return I18n.GetByKey("labels.stack-price");
}
/*********
** Private methods
*********/
/// <summary>通过KEY获取翻译后对应的文本</summary>
/// <param name="key">JSON KEY</param>
/// <param name="tokens">令牌,貌似没发现如何用</param>
private static Translation GetByKey(string key, object tokens = null)
{
// 保证在读取翻译文件前从mod中获取到设置的语言
if (I18n.Translations == null)
throw new InvalidOperationException($"You must call {
nameof(I18n)}.{
nameof(I18n.Init)} from the mod's entry method before reading translations.");<