u3dchina_Unity_tolua基础教学2_c#调lua
demo中有详细的例子说明:====c#调用tolua静态方法
我们来自己写一个:
新建一个TestLua.cs脚本,脚本如下:using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LuaInterface;
using System;
public class TestLua : MonoBehaviour
{
private LuaState luaState;
private LuaFunction luaFunc = null;//lua函数
private string strLog = "";
// Start is called before the first frame update
void Start()
{
luaState= new LuaState(); // 创建lua虚拟机
Application.RegisterLogCallback(Log);
luaState.Start();
string fullPath = Application.dataPath + "\\ToLua/Test";
luaState.AddSearchPath(fullPath);
}
void Log(string msg, string stackTrace, LogType type)
{
strLog += msg;
strLog += "\r\n";
}
//自定义功能函数,将被注册到lua虚拟机中
public string CSharpMethod(int num)
{
return string.Format("Hello World {0} !" , num+1);
}
private void OnGUI()
{
GUI.Label(new Rect(100, Screen.height / 2 - 100, 600, 400), strLog);
if (GUI.Button(new Rect(50, 50, 120, 45), "DoFile"))
{
strLog = "";
luaState.DoFile("TestLua.lua");
luaFunc = luaState.GetFunction("test.luaFunc");//这里test 可以去掉
if (luaFunc!=null)
{
// 加载完文件后,使用GetFunction获取lua脚本中的函数,再调用Call执行。
intnum = luaState.Invoke<int, int>("test.luaFunc", 123456, true);
Debugger.Log("c#调用lua", num);
}
}
else if (GUI.Button(new Rect(50, 150, 120, 45), "Require"))
{
strLog = "";
luaState.Require("TestLua");
}
luaState.Collect();
luaState.CheckTop();
}
void OnApplicationQuit()
{
luaState.Dispose();
luaState = null;
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived -= Log;
#else
Application.RegisterLogCallback(null);
#endif
}
// Update is called once per frame
void Update()
{
}
}
注意路径要指定,在新建一个lua文件为TestLua.lua,内容为:function luaFunc(num)
return num + 1
end
test = {}
test.luaFunc = luaFunc这里讲解了通过Invoke的方法调用lua代码。
--
在C#中加载lua文件(LuaState.DoFile)
拿到目标函数(LuaState.GetFunction)
通过Invoke调用目标函数lua中静态方法test.luaFunc
页:
[1]