ToLua 笔记

2019-08-27  本文已影响0人  周末的游戏之旅

ToLua 下载及导入

ToLua 下载 :https://github.com/topameng/tolua

下载完毕后 将Assets和Unity 5.x 覆盖到项目的跟目录

ToLua 目录

Assets/Editor/Custom/CustomSetting.cs
用于注册自定义类型,ToLua已经提供了Unity的大部分基础类型,如果要导入自定义的类型可以在其中添加。

Assets/Source/LuaConst.cs
存放Lua路径的配置文件。

Assets/Source/Generate/
生成的交互绑定代码的warp脚本存放在这个目录中。C#和Lua的交互主要靠这些脚本来进行。

Assets/ToLua/BaseType/
存放基础类型绑定代码的warp脚本

Assets/ToLua/Core/
ToLua提供的核心功能

注册自定义类型

  1. 创建C#脚本
  2. 在CustomSetting中的customTypeList中添加新创建的脚本类型
  3. 在unity界面中选择lua-clear warp files

脚本示例

-- 声明一个表格来模拟类
Controller={}
-- 模拟类中的this
local this = Controller
-- 声明需要用到的组件
local GameObjct = UnityEngine.GameObjct
local Input = UnityEngine.Input
local Rigidbody = UnityEngine.Rigidbody
local Color = UnityEngine.Color

-- 声明一些局部变量
local Sphere
local rigi
local force

function this.Start()
    Sphere·GameObject.Find('Sphere')
    Sphere:GetComponent('Renderer').material.color=Color(1,0.1,1)
    Sphere:AddComponent(typeof(Rigibody))
    rigi=Sphere:GetComponent('Rigidbody')
    force=5
end

function this.Update()
    local h=Input.GetAxis('Horizontal')
    local y=Input.GetAxis('Vertical')
    rigt:AddForce(Vector3(h,0,v)*force)
end
using UnityEngine;
using System.Collections;
using LuaInterface; //引入命名空间

public class LUATEST : MonoBehaviour {

    //声明lua虚拟机
    private LuaState lua = null;

    private LuaFunction luaFunc = null;

    void Start () {
        //自定义lua加载器,加载lua文件
        new LuaResLoader();
        //初始化lua虚拟机
        lua = new LuaState();
        //开启lua虚拟机
        lua.Start();
        //向虚拟机注册C#类型
        LuaBinder.Bind(lua);
        //添加自定义的lua脚本路径
        lua.AddSearchPath(Application.streamingAssetsPath+"\\Lua");
        //执行lua脚本
        lua.DoFile("Fire.lua");
        
        CallFunc("Controller.Start");
    }

    private void Update() {
        
        CallFunc("Controller.Update");
    }

    void CallFunc(string func)
    {
        luaFunc = lua.GetFunction(func);
        luaFunc.Call();
    }
}
上一篇下一篇

猜你喜欢

热点阅读