LocString 占位符解析
本文档分为两部分:游戏原版机制(LocString、SmartFormat 配置、内置格式化器)和扩展指南(Mod 如何注册自定义 IFormatter)。
第一部分:游戏原版机制
核心组件
LocString:持有本地化表 id、条目键与变量字典,调用GetFormattedText()执行格式化。LocManager.SmartFormat:从LocTable取原始模板,根据键是否已本地化选择CultureInfo,再由SmartFormatter.Format(...)解析。LocManager.LoadLocFormatters:初始化SmartFormatter,注册数据源与格式化器扩展。
变量绑定
变量通过 LocString.Add 写入字典,名称中的空格会被替换为连字符。
csharp
var locString = new LocString("cards", "strike");
locString.Add("damage", 6);
string result = locString.GetFormattedText();占位符语法
游戏本地化 JSON 中使用 SmartFormat 占位符。
仅变量名 — 直接输出变量值:
{VariableName}指定格式化器 — 格式化器以函数调用形式写在冒号后:
{VariableName:formatterName()}
{VariableName:formatterName(options)}带额外格式段的格式化器(如 show、choose、cond)在调用后通过第二个冒号传递格式文本。
示例:
json
{
"damage_text": "对所有敌人造成 {Damage:diff()} 点伤害。",
"energy_text": "本回合获得 {Energy:energyIcons()}。"
}游戏自定义格式化器
游戏在 MegaCrit.Sts2.Core.Localization.Formatters 中注册了以下 IFormatter:
IFormatter.Name | 占位符写法 | 说明 |
|---|---|---|
abs | {v:abs()} | 输出数值的绝对值 |
energyIcons | {Energy:energyIcons()} | 将数值渲染为能量图标 |
starIcons | {v:starIcons()} | 将数值渲染为星星图标 |
diff | {v:diff()} | 以绿色高亮显示数值变化 |
inverseDiff | {v:inverseDiff()} | 与 diff 相同但颜色方向相反 |
percentMore | {v:percentMore()} | 将乘数转换为增加百分比 |
percentLess | {v:percentLess()} | 将乘数转换为减少百分比 |
show | {v:show:升级文案|普通文案} | 根据升级状态条件显示文案 |
DynamicVar 类型
DynamicVar 子类携带格式化元数据:
| 类型 | 说明 |
|---|---|
DamageVar | 伤害值,携带高亮元数据 |
BlockVar | 格挡值 |
EnergyVar | 能量值,携带颜色信息 |
CalculatedVar | 计算值基类 |
BoolVar / IntVar / StringVar | 基础类型 |
GoldVar / HealVar / HpLossVar / MaxHpVar | 资源类型 |
PowerVar<T> | 能力值(泛型) |
IfUpgradedVar | 升级显示状态 |
高级示例
条件格式(ConditionalFormatter):
json
{ "text": "{HasRider:此卡有附加效果|此卡无附加效果}" }选择格式(ChooseFormatter):
json
{ "text": "{CardType:choose(Attack|Skill|Power):攻击文本|技能文本|能力文本}" }嵌套格式化器:
json
{
"text": "{Violence:造成 {Damage:diff()} 点伤害 {ViolenceHits:diff()} 次|造成 {Damage:diff()} 点伤害}"
}BBCode 颜色标签:
json
{ "text": "获得 [gold]{Gold}[/gold] 金币,当前生命 [green]{Hp}[/green]。" }常用标签:[gold]、[green]、[red]、[blue]。
第二部分:自定义格式化器(Mod)
通过对 LocManager.LoadLocFormatters 打 Postfix 补丁,可在 SmartFormatter 中注册额外的 IFormatter 实现。
实现 IFormatter:
csharp
public class MyCustomFormatter : IFormatter
{
public string Name { get => "myCustom"; set { } }
public bool CanAutoDetect { get; set; }
public bool TryEvaluateFormat(IFormattingInfo formattingInfo)
{
formattingInfo.Write($"自定义输出: {formattingInfo.CurrentValue}");
return true;
}
}注册补丁:
csharp
public class RegisterMyFormatterPatch : IPatchMethod
{
public static string PatchId => "register_my_formatter";
public static string Description => "Register custom SmartFormat formatter";
public static bool IsCritical => true;
public static ModPatchTarget[] GetTargets()
=> [new(typeof(LocManager), "LoadLocFormatters")];
public static void Postfix(SmartFormatter ____smartFormatter)
=> ____smartFormatter.AddExtensions(new MyCustomFormatter());
}注册后,在 JSON 中通过 {SomeVar:myCustom()} 或 {SomeVar:myCustom(args)} 调用。