之前讲过了怎么在unity中调用lua脚本,和一些常用的使用方式;之前说到了在lua中使用协程,并在unity中使用,实际上在unity中也只是普通调用方法方式,只是在unity中做出了封装,对lua脚本中的协程进行特殊调用处理。
Lua脚本中无法直接使用unity内置的类和方法,下面我们就讲一下lua中使用unity内置对象。
大家先打开lua框架中的示范工程tolua-master\Assets\ToLua\Examples中的示范场景,可以先体验运行一下内置场景。我们打开内置的TestGameObject示范类,并对齐进行修改,修改为打开使用外部文件进行调用。修改后的脚本如下:
using UnityEngine;
using System.Collections;
using LuaInterface;
public class TestGameObject: MonoBehaviour
{
LuaState lua = null;
void Start()
{
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived += ShowTips;
#else
Application.RegisterLogCallback(ShowTips);
#endif
new LuaResLoader();
lua = new LuaState();
lua.LogGC = true;
lua.Start();
//添加自定义的lua脚本路径
LuaBinder.Bind(lua);
//lua文件路径
string fullPath = Application.dataPath + "\\ToLua/Examples/12_GameObject";
//添加lua文件路径
lua.AddSearchPath(fullPath);
lua.DoFile("TestGameObject.lua");
}
void Update()
{
lua.CheckTop();
lua.Collect();
}
string tips = "";
void ShowTips(string msg, string stackTrace, LogType type)
{
tips += msg;
tips += "\r\n";
}
void OnApplicationQuit()
{
lua.Dispose();
lua = null;
#if UNITY_5 || UNITY_2017 || UNITY_2018
Application.logMessageReceived -= ShowTips;
#else
Application.RegisterLogCallback(null);
#endif
}
void OnGUI()
{
GUI.Label(new Rect(Screen.width / 2 - 300, Screen.height / 2 - 300, 600, 600), tips);
}
}
LuaBinder.Bind(lua);将框架默认绑定的unity内置的模块加载进内存。
AddSearchPath 加载lua的文件夹。
lua.DoFile(“TestGameObject.lua”); 执行lua文件夹的TestGameObject.lua文件。
在代码的运行下,大家可以看见有个名字“123”的空物体对象生成,并绑定了一个默认的例子组件,然后2秒后删除。我们接下来对TestGameObject.lua文件进行分析。
--引用unity内置类
local Color = UnityEngine.Color
local GameObject = UnityEngine.GameObject
local ParticleSystem = UnityEngine.ParticleSystem
function OnComplete()
print('OnComplete CallBack')
end
local go = GameObject('go') --新建go游戏对象
go:AddComponent(typeof(ParticleSystem)) --游戏对象添加ParticleSystem组件
local node = go.transform
node.position = Vector3.one --设置对象位置
print('gameObject is: '..tostring(go))
GameObject.Destroy(go, 2) --延迟2s删除对象
go.name = '123' --对象改名为123
重点是引用unity内置对象,逻辑写法与在unity中用C# 一样,只是lua语法与C#不太一样。