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;

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#不太一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值