这里先贴出官方脚本
[System.Serializable]
public class Injection
{
public string name;
public GameObject value;
}
[LuaCallCSharp]
public class LuaBehaviour : MonoBehaviour
{
public TextAsset luaScript;
public Injection[] injections;
internal static LuaEnv luaEnv = new LuaEnv(); //all lua behaviour shared one luaenv only!
internal static float lastGCTime = 0;
internal const float GCInterval = 1;//1 second
private Action luaStart;
private Action luaUpdate;
private Action luaOnDestroy;
private LuaTable scriptEnv;
void Awake()
{
scriptEnv = luaEnv.NewTable();
// 为每个脚本设置一个独立的环境,可一定程度上防止脚本间全局变量、函数冲突
LuaTable meta = luaEnv.NewTable();
meta.Set("__index", luaEnv.Global);
scriptEnv.SetMetaTable(meta);
meta.Dispose();
scriptEnv.Set("self", this);
foreach (var injection in injections)
{
scriptEnv.Set(injection.name, injection.value);
}
luaEnv.DoString(luaScript.text, "LuaTestScript", scriptEnv);
Action luaAwake = scriptEnv.Get<Action>("awake");
scriptEnv.Get("start", out luaStart);
scriptEnv.Get("update", out luaUpdate);
scriptEnv.Get("ondestroy", out luaOnDestroy);
if (luaAwake != null)
{
luaAwake();
}
}
// Use this for initialization
void Start()
{
if (luaStart != null)
{
luaStart();
}
}
// Update is called once per frame
void Update()
{
if (luaUpdate != null)
{
luaUpdate();
}
if (Time.time - LuaBehaviour.lastGCTime > GCInterval)
{
luaEnv.Tick();
LuaBehaviour.lastGCTime = Time.time;
}
}
void OnDestroy()
{
if (luaOnDestroy != null)
{
luaOnDestroy();
}
luaOnDestroy = null;
luaUpdate = null;
luaStart = null;
scriptEnv.Dispose();
injections = null;
}
}
}
print('LuaTestScript------>加载成功')
local speed = 10
local lightCpnt = nil
function awake()
print(self.name)
end
function start()
print("lua start...")
print("injected object", lightObject)
lightCpnt= lightObject:GetComponent(typeof(CS.UnityEngine.Light))
end
function update()
local r = CS.UnityEngine.Vector3.up * CS.UnityEngine.Time.deltaTime * speed
self.transform:Rotate(r)
lightCpnt.color = CS.UnityEngine.Color(CS.UnityEngine.Mathf.Sin(CS.UnityEngine.Time.time) / 2 + 0.5, 0, 0, 1)
end
function ondestroy()
print("lua destroy")
end
我的问题
在官方案例中,通过 luaEnv.DoString(luaScript.text, “LuaTestScript”, scriptEnv); 直接加载Lua文本后,在 LuaTestScript.lua 中的变量 self 是指向LuaBehavior的。
而我尝试通过路径加载Lua,在 LuaTestScript.lua 中的变量 self 是空的。示例如下:
//省略上面代码
//假设路径正确,且加载成功
string luaScriptPath ="XXX/LuaTestScript.lua";
luaEnv.DoString($"require('{luaScriptPath}')", "LuaTestScript", scriptEnv);
//省略下面代码
报错如下
这算是Bug吗?