常用游戏 APICommon game APIs
Lua 程序 Mod 与 DLL Mod 在运行时最常调用的游戏接口:查配置表、取文本、弹提示、写日志、读地图格、读写存档数据。签名从源码抄录,用途取自现有 Mod 的实际用法。 The game interfaces Lua program mods and DLL mods call most at runtime: looking up definitions, text, toasts, logging, map cells and save data. Signatures are copied from source; purposes come from how existing mods use them.
三层接口,稳定性不同Three tiers with different stability
| 层Tier | 内容What | 游戏更新时On game updates |
|---|---|---|
| 正式扩展点Extension points | 清单与目录、def.xml、Lua 四个回调、BaseModLauncher / BaseModDefLoader、ModDelegateDispatch、剧情脚本的 mission。见 API 参考。Manifest and layout, def.xml, the four Lua callbacks, BaseModLauncher / BaseModDefLoader, ModDelegateDispatch, the story-script mission. See the API reference. | 为 Mod 设计,改动会同步到本站。Designed for mods; changes are reflected on this site. |
| 游戏内部的公开成员Public game internals | 本页列出的类与方法。它们是游戏自己的代码,只是恰好是 public。The classes and methods on this page. They are the game's own code that happens to be public. | 可能改名或改签名,不另行通知。每次更新后重测。May be renamed or re-signed without notice. Retest after every update. |
| Harmony 补丁Harmony patches | 用补丁改写任意方法,包括私有方法。仅 PC 的 DLL Mod。Rewriting any method, private ones included. PC DLL mods only. | 最容易失效;方法体变化即可能出错。Breaks first; any change to the method body can do it. |
Assembly-CSharp.dll,所以可调用的远不止本页。本页只收录已核对签名、且被多个现有 Mod 使用的入口;其余请以游戏程序集为准。
On PC, Lua reaches nearly every public type by reflection and DLLs reference Assembly-CSharp.dll directly, so far more is callable than this page lists. Only entries with checked signatures that several existing mods use are included; for anything else the game assembly is authoritative.
Lua 里怎么调用 C#Calling C# from Lua
| C# | Lua (xLua) |
|---|---|
静态方法 / 字段Static method / fieldMapTools.isCellInMapRect(x, y) | CS.MapTools.isCellInMapRect(x, y)用点号dot |
实例方法Instance methodnode.isInFog() | node:isInFog()用冒号colon |
| 实例字段 / 属性Instance field / property | node.roomBean, row.Price = 10 |
| 命名空间里的类型Namespaced type | CS.UnityEngine.Vector2Int(1, 2) |
List<T> | for i = 0, list.Count - 1 do local x = list[i] end下标从 0 开始0-based index |
typeof(T) | typeof(CS.Struct_Door) |
| Unity 对象判空Unity object null check | obj ~= nil and not obj:Equals(nil)已销毁的对象在 Lua 里不等于 nila destroyed object is not nil in Lua |
以上写法都取自仓库内正在使用的 Lua Mod,在编辑器(Mono)中运行过。手机正式包上的可用范围见 IL2CPP 限制。 All of these come from Lua mods in use in the repository and ran in the editor (Mono). For what works in mobile release builds see IL2CPP limits.
配置表Definitions
T 是任意配置表类,例如 T_FoodDef;全部表见配置表参考。T is any table class such as T_FoodDef; all tables are in the table reference.
| 签名Signature | 用途Purpose |
|---|---|
static List<T> T.beans | 整张表的所有行。“配置表就绪”时机只能用它遍历。Every row of the table. At the “definitions ready” hook this is the only way to find rows. |
static T T.getDataID(string id) | 按 ID 取行。ID 索引建好之后才可用(进入游戏后),见加载流程。Row by ID. Works only after the ID index is built (once in game); see Load pipeline. |
static T T.getTemplateDef(string id) | 返回该行的深拷贝,用来做新行的模板。A deep copy of the row, for use as a template. |
void BaseModDefLoader.addRow<T>(T row) | DLL:把新行加入表,ID 自动加包前缀并记录所属 Mod。在 initModDef() 里调用。DLL: adds a row, prefixing its ID and recording the owning mod. Call it from initModDef(). |
-- Lua, onDefLoaded: 遍历 beans 修改原版行iterate beans to edit a built-in row
local beans = CS.T_FoodDef.beans
for i = 0, beans.Count - 1 do
local row = beans[i]
if row.ID == '3' then row.Price = row.Price * 2 end
end
文本Text
| 签名Signature | 用途Purpose |
|---|---|
static string LanguageDef.getTextByID(string key) | 按当前语言取文本。key 不带 id_ 前缀;找不到时返回 key 本身。Text in the current language. key has no id_ prefix; a missing key returns key itself. |
static string LanguageDef.getTextByID(string key, string fallback) | 同上,找不到时返回 fallback。Same, returning fallback when missing. |
static bool LanguageDef.HasText(string key) | 语言表里是否有这个 Key。Whether the language table has the key. |
Mod 自己的文本用 def.xml 的 LanguageDef 行提供,见文本与多语言。Provide your own text through LanguageDef rows in def.xml; see Text & localisation.
提示与日志Toasts and logging
| 签名Signature | 用途Purpose |
|---|---|
static UIToast FairyUIDispatcher.showToast(string content, bool waitLine = false) | 屏幕提示一行文字。A one-line on-screen toast. |
static TipPoolDat FairyUIDispatcher.showTip(string text, string confirmText, string centleText, TipDelegate dele, bool isCanClose = true, int tipType = TipPoolDat.TIP_TYPE_TIP) | 确认框。回调参数为 Tip.TIP_CONFIRM 或 Tip.TIP_CANCEL。A confirm box. The callback receives Tip.TIP_CONFIRM or Tip.TIP_CANCEL. |
static void Logger.LogEngine(string str)static void Logger.LogWarningEngine(string str)static void Logger.LogErrorEngine(string str)static void Logger.LogErrorEngine(Exception e) | 写入游戏日志(位置见排错)。在日志开头写上自己的 Mod 名,方便玩家反馈。不要每帧写。Writes to the game log (location in Troubleshooting). Start messages with your mod's name so players can report them. Never log every frame. |
Lua 里 print(...) 同样写入日志,带 LUA: 前缀。In Lua, print(...) also goes to the log, prefixed with LUA:.
地面地图与格子Ground map and cells
| 签名Signature | 用途Purpose |
|---|---|
static MapManager MapManager.getInstance() | 当前地面地图。常用成员:planManager、roomManage、camearControl、heroManager。不在地面场景时为 null。The current ground map. Common members: planManager, roomManage, camearControl, heroManager. null outside the ground scene. |
static bool MapManager.isInitFinishstatic bool MapManager.isRuning | 地图是否初始化完成、逻辑是否在运行。每帧逻辑先检查这两项。Whether the map finished initialising and whether simulation is running. Check both before per-frame work. |
static float MapManager.getNowSpeed() | 当前游戏倍速。Current game speed multiplier. |
static bool MapTools.isCellInMapRect(int cellX, int cellY) | 格坐标是否在地图范围内。取格子前先判断。Whether a cell is inside the map. Check before fetching a cell. |
static GridNode MapGrid.getGridNode(int cellx, int celly) | 取一格。常读成员:build、floor、platform、electricLine、floorLamp、roomBean、isInFog()。One cell. Commonly read: build, floor, platform, electricLine, floorLamp, roomBean, isInFog(). |
static bool PassableHandler.isPersonPassable(int cellx, int celly, SpriteObject role = null) | 该格角色能否通行。Whether a character can walk on the cell. |
const int MapGlobal.cellWidth = 32const int MapGlobal.cellHeight = 32static int MapGlobal.mapStartX / mapStartY | 格子尺寸与地图原点,用于格坐标与世界坐标换算。Cell size and map origin, for converting between cell and world coordinates. |
static bool UIUntils.isGameSceneLoading() | 是否正在切换 / 加载场景。Whether a scene is switching / loading. |
-- Lua, onUpdate: 先确认地图可用,再读格子make sure the map is usable before reading cells
local function mapReady()
return CS.MapManager.isInitFinish and CS.MapManager.isRuning
and not CS.UIUntils.isGameSceneLoading()
end
local function buildAt(x, y)
if not mapReady() or not CS.MapTools.isCellInMapRect(x, y) then return nil end
local node = CS.MapGrid.getGridNode(x, y)
if node == nil or node:isInFog() then return nil end
return node.build
end
玩家与存档数据Player and save data
| 签名Signature | 用途Purpose |
|---|---|
static UserBean UserBean.tryGetInstance() | 当前玩家数据,没有时返回 null。Mod 里用这个,不要用会新建实例的 getInstance()。The current player data, or null. Use this in mods rather than getInstance(), which creates an instance. |
FWGameData UserBean.gameDataUserFWStarSpread UserBean.curStarMap | 当前存档数据、当前所在地图。读档或换地图后引用会变,用它判断上下文是否还是原来那个。Current save data and current map. The references change on load or map switch — use them to detect a context change. |
long FWGameData.elapsedMM | 游戏内已过时间(毫秒)。Elapsed in-game time in milliseconds. |
List<ET_RecordBean> FWGameData.ET_LuaRecords | 随存档保存的键值记录。每条有 key 和 longValue / floatValue / boolValue。Key–value records saved with the save file. Each has a key and longValue / floatValue / boolValue. |
object FWGameData.ArchiveSyncRoot | 存档数据的锁对象。DLL 中读写 ET_LuaRecords 时先 lock 它。The lock object for save data. In a DLL, lock it before touching ET_LuaRecords. |
ET_LuaRecords,Key 用自己的包名做前缀。不要把 Mod DLL 里定义的类型直接挂到存档对象上——那些内容不会被保存。写入了存档的 Mod 一旦被停用,存档里会留下无人认领的记录。
Getting mod state into saves. There is no dedicated mod save API. Existing mods split their state into numbers and store them in ET_LuaRecords under keys prefixed with their package name. Don't attach types defined in your DLL to save objects — they are not saved. Once a mod that wrote records is disabled, its records stay in the save unclaimed.
线程Threads
| 签名Signature | 用途Purpose |
|---|---|
static bool MainThread.onMain | 当前是否在主线程。Whether the caller is on the main thread. |
static void MainThread.post(Action action) | 把操作排到主线程执行,不等待;已在主线程时立即执行。Queues work on the main thread without waiting; runs immediately if already on it. |
static void MainThread.invoke(Action action)static T MainThread.invoke<T>(Func<T> func) | 在主线程执行并等待完成。Runs on the main thread and waits for the result. |
地面逻辑有一部分在模拟线程上运行。DLL 的 Harmony 补丁可能在非主线程被调用;这时访问 Unity 对象或界面要先转到主线程。Lua 的回调始终在主线程。Part of the ground simulation runs on a simulation thread. Harmony patches in a DLL may be invoked off the main thread; switch to the main thread before touching Unity objects or UI. Lua callbacks always run on the main thread.
地面指令(计划)Ground orders (plans)
玩家下达的建造、拆除、搬运等指令在代码里叫“计划”。这些入口与玩家点击界面走的是同一条路径。Build, dismantle, haul and similar player orders are called “plans” in code. These entries follow the same path as the player's own clicks.
| 签名Signature | 用途Purpose |
|---|---|
static BasePlanGraph LocalCoreHandle.Plan_addNewPlan_LN(FWPlanBean newPlan) | 新增一条计划。Adds a plan. |
static void LocalCoreHandle.Plan_removePlan_LN(RolePlan plan) | 移除一条计划。Removes a plan. |
static void LocalCoreHandle.Plan_DoPrior_LN(BasePlanGraph graph, bool flag) | 设置 / 取消优先。Sets or clears priority. |
static void LocalCoreHandle.Plan_CacheUpdate_LN(bool gmEnable = false) | 提交本次批量创建的计划。Commits the plans created in this batch. |
static BasePlanGraph ViewBuild_Fctions_Base.createBuildsPlan(BaseBuild zoneBuild, short planType) | 对一个建筑创建指定类型的计划,如 FWPlanBean.TASK_Uninstall。Creates a plan of the given type for a building, e.g. FWPlanBean.TASK_Uninstall. |
Lua 能做与只能用 DLL 做的事What Lua can do and what needs a DLL
| 需求Need | Lua | DLL |
|---|---|---|
| 修改原版配置行Edit built-in definition rows | ✓ onDefLoaded | ✓ initModDef() |
| 每帧读取状态并调整表现Read state each frame and adjust presentation | ✓ onUpdate | ✓ |
| 在游戏某个方法执行前后插入逻辑Run logic before or after a game method | ✗ 只能下一帧发现变化can only notice changes next frame | ✓ Harmony |
| 改变游戏内部调用的结果(校验、工时、结算)Change the result of internal calls (validation, work amounts, settlement) | ✗ | ✓ Harmony |
| 定义新的 C# 类、继承游戏类(如自定义建筑类)Define C# classes or derive from game classes (e.g. custom building classes) | ✗ | ✓ |
| 在手机上运行Run on mobile | ✓* | ✗ |
| 退出时得到清理回调Get a cleanup callback on unload | ✓ onUnload | ✗ |
* 受 IL2CPP 限制。游戏当前对 Mod 开放的事件只有 ModDelegateDispatch 的两个建筑生成事件,因此“某件事发生时通知我”这类需求,Lua 只能靠 onUpdate 轮询。轮询时缓存上次的结果,只在变化时处理,避免每帧分配和全图扫描。
* Subject to IL2CPP limits. The only events the game exposes to mods today are the two building-generation events on ModDelegateDispatch, so “tell me when X happens” needs polling from onUpdate in Lua. When polling, cache the previous result and act only on change; avoid per-frame allocations and full-map scans.