快速开始
先完成 安装与集成 中的 Settings → Install。克隆 Demo 后也需要完成本地 Install。本文在 Editor 中验证双向调用;Player 另见 首次构建。
1. 创建 C# 入口
将以下完整文件保存为 Assets/Bootstrap.cs。无需挂到场景对象;初始化方法会自动执行。
using System;
using System.IO;
using System.Text;
using UnityEngine;
using ZLua;
public static class Bootstrap
{
private static string LoadLuaModule(string module)
{
string relativePath = module.Replace('.', '/') + ".lua";
string path = Path.Combine(Application.dataPath, "..", "LuaScripts", relativePath);
if (!File.Exists(path))
{
throw new FileNotFoundException($"Lua module '{module}' not found", path);
}
return File.ReadAllText(path, Encoding.UTF8);
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void Initialize()
{
LuaAppDomain.Initialize(LoadLuaModule);
Action main = LuaAppDomain.GetFunction<Action>("app", "main");
Func<int, int, int> add = LuaAppDomain.GetFunction<Func<int, int, int>>("app", "add");
main();
Debug.Log($"Lua add: {add(10, 20)}");
}
}
创建 Assets/Demo.cs:
public class Demo
{
public int x;
public static int Add(int a, int b) => a + b;
}
2. 创建 Lua 模块
在项目根创建 LuaScripts/app.lua(与 Assets 同级的 LuaScripts 目录):
local Demo = CSharp['Assembly-CSharp'].Demo
local function main()
local instance = Demo()
instance.x = 10
print("C# Add: " .. Demo.Add(3, 5))
print("C# field: " .. instance.x)
end
local function add(a, b)
return a + b
end
return { main = main, add = add }
GetFunction 加载模块的返回表,按键找到函数并返回委托。Lua 通过 CSharp[程序集名] 找到 C# 类型,静态方法使用点号,实例方法使用冒号。
3. 验证
打开任意场景并 Play,Console 应依次包含:
C# Add: 8
C# field: 10
Lua add: 30
找不到模块时检查文件位置;找不到 Demo 时检查程序集名(使用 asmdef 的项目应改为实际程序集名)。同一进程已有 Lua 域时不要再次 Initialize;生命周期见 LuaAppDomain。
下一步
继续 首次构建 Il2Cpp Player,为 loader 增加 Player 脚本路径与资源加载。本文 loader 专用于 Editor;Android / WebGL 等平台应先用项目资源系统取得脚本,再交给同步 loader。