johnsoncodehk 发表于 2021-8-11 17:17

ToLua 入门07_GameObject

之前讲过了怎么在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;publicclassTestGameObject:MonoBehaviour{LuaState lua =null;voidStart(){#if UNITY_5 || UNITY_2017 || UNITY_2018
      Application.logMessageReceived += ShowTips;#else
      Application.RegisterLogCallback(ShowTips);#endifnewLuaResLoader();
      lua =newLuaState();
      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");}voidUpdate(){
      lua.CheckTop();
      lua.Collect();}string tips ="";voidShowTips(string msg,string stackTrace,LogType type){
      tips += msg;
      tips +="\r\n";}voidOnApplicationQuit(){      
      lua.Dispose();
      lua =null;#if UNITY_5 || UNITY_2017 || UNITY_2018
      Application.logMessageReceived -= ShowTips;#else
      Application.RegisterLogCallback(null);#endif}voidOnGUI(){
      GUI.Label(newRect(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#不太一样。
页: [1]
查看完整版本: ToLua 入门07_GameObject