xLua——用lua来写MonoBehaviour

作者:追风剑情 发布于:2017-7-15 17:11 分类:Lua

以下代码来自xLua demo,这里只是进一步做下解释。

一、Lua文件

local speed = 10

function start()
	print("lua start...")
end

function update()
	local r = CS.UnityEngine.Vector3.up * CS.UnityEngine.Time.deltaTime * speed
	self.transform:Rotate(r)
end

function ondestroy()
    print("lua destroy")
end

二、C#文件

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;

[System.Serializable]
public class Injection
{
    public string name;
    public GameObject value;
}

[LuaCallCSharp]
public class LuaBehaviour : MonoBehaviour {
    public TextAsset luaScript;
    public Injection[] injections;

    internal static LuaEnv luaEnv = new LuaEnv(); //all lua behaviour shared one luaenv only!
    internal static float lastGCTime = 0;
    internal const float GCInterval = 1;//1 second 

    private Action luaStart;
    private Action luaUpdate;
    private Action luaOnDestroy;

    private LuaTable scriptEnv;

    void Awake()
    {
        scriptEnv = luaEnv.NewTable();

        //以K-V方式绑定一些C#对象到Lua代码类(NewTable)
        LuaTable meta = luaEnv.NewTable();
        meta.Set("__index", luaEnv.Global);
        scriptEnv.SetMetaTable(meta);
        meta.Dispose();

        scriptEnv.Set("self", this);
        foreach (var injection in injections)
        {
            scriptEnv.Set(injection.name, injection.value);
        }

        //加载并编译Lua代码
        //参数1: 要编译的Lua代码字符串
        //参数2: 执行代码报错时要显示的信息
        //参数3: 把加载的Lua代码封装到一个NewTable类中
        luaEnv.DoString(luaScript.text, "LuaBehaviour", scriptEnv);

        //将Lua函数绑定到C#的delegate变量上
        Action luaAwake = scriptEnv.Get<Action>("awake");
        scriptEnv.Get("start", out luaStart);
        scriptEnv.Get("update", out luaUpdate);
        scriptEnv.Get("ondestroy", out luaOnDestroy);

        if (luaAwake != null)
        {
            luaAwake();//调用Lua版Awake()
        }
    }

	void Start ()
    {
        if (luaStart != null)
        {
            luaStart();//调用Lua版Start()
        }
	}
	
	void Update ()
    {
        if (luaUpdate != null)
        {
            luaUpdate();//调用Lua版Update()
        }
        //定期清除Lua中未手动清除的绑定
        if (Time.time - LuaBehaviour.lastGCTime > GCInterval)
        {
            luaEnv.Tick();//清除绑定
            LuaBehaviour.lastGCTime = Time.time;
        }
	}

    void OnDestroy()
    {
        if (luaOnDestroy != null)
        {
            luaOnDestroy();//调用Lua版OnDestroy()
        }
        //释放所有资源
        luaOnDestroy = null;
        luaUpdate = null;
        luaStart = null;
        scriptEnv.Dispose();
        injections = null;
    }
}

工程截图

2222.png

运行测试

11111.png

标签: xLua

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号