Unity3D UniLua的示例

LuaScriptController
using System;
using System.Collections;
using UnityEngine;
using UniLua;

public class LuaScriptController : MonoBehaviour
{
    public string LuaScriptFile = "framework/main.lua";

    private ILuaState Lua;
    private int AwakeRef;
    private int StartRef;
    private int UpdateRef;
    private int LateUpdateRef;
    private int FixedUpdateRef;

    void Awake()
    {
        Debug.Log("LuaScriptController Awake");

        if (Lua == null)
        {
            Lua = LuaAPI.NewState();
            Lua.L_OpenLibs();

            var status = Lua.L_DoFile(LuaScriptFile);
            if (status != ThreadStatus.LUA_OK)
            {
                throw new Exception(Lua.ToString(-1));
            }

            if (!Lua.IsTable(-1))
            {
                throw new Exception(
                    "framework main's return value is not a table");
            }

            AwakeRef = StoreMethod("awake");
            StartRef = StoreMethod("start");
            UpdateRef = StoreMethod("update");
            LateUpdateRef = StoreMethod("late_update");
            FixedUpdateRef = StoreMethod("fixed_update");

            Lua.Pop(1);
            Debug.Log("Lua Init Done");
        }

        CallMethod(AwakeRef);
    }

    IEnumerator Start()
    {
        CallMethod(StartRef);

        // -- sample code for loading binary Asset Bundles --------------------
        String s = "file:///" + Application.streamingAssetsPath + "/testx.unity3d";
        WWW www = new WWW(s);
        yield return www;
        if (www.assetBundle.mainAsset != null)
        {
            TextAsset cc = (TextAsset)www.assetBundle.mainAsset;
            var status = Lua.L_LoadBytes(cc.bytes, "test");
            if (status != ThreadStatus.LUA_OK)
            {
                throw new Exception(Lua.ToString(-1));
            }
            status = Lua.PCall(0, 0, 0);
            if (status != ThreadStatus.LUA_OK)
            {
                throw new Exception(Lua.ToString(-1));
            }
            Debug.Log("---- call done ----");
        }
    }

    void Update()
    {
        CallMethod(UpdateRef);
    }

    void LateUpdate()
    {
        CallMethod(LateUpdateRef);
    }

    void FixedUpdate()
    {
        CallMethod(FixedUpdateRef);
    }

    private int StoreMethod(string name)
    {
        Lua.GetField(-1, name);
        if (!Lua.IsFunction(-1))
        {
            throw new Exception(string.Format(
                "method {0} not found!", name));
        }
        return Lua.L_Ref(LuaDef.LUA_REGISTRYINDEX);
    }

    private void CallMethod(int funcRef)
    {
        Lua.RawGetI(LuaDef.LUA_REGISTRYINDEX, funcRef);

        // insert `traceback' function
        var b = Lua.GetTop();
        Lua.PushCSharpFunction(Traceback);
        Lua.Insert(b);

        var status = Lua.PCall(0, 0, b);
        if (status != ThreadStatus.LUA_OK)
        {
            Debug.LogError(Lua.ToString(-1));
        }

        // remove `traceback' function
        Lua.Remove(b);
    }

    private static int Traceback(ILuaState lua)
    {
        var msg = lua.ToString(1);
        if (msg != null)
        {
            lua.L_Traceback(lua, msg, 1);
        }
        // is there an error object?
        else if (!lua.IsNoneOrNil(1))
        {
            // try its `tostring' metamethod
            if (!lua.L_CallMeta(1, "__tostring"))
            {
                lua.PushString("(no error message)");
            }
        }
        return 1;
    }
}


main.lua

local InputControl  = require "logic.input_control"
local SceneMgr      = require "logic.scene_mgr"
local UnityEngine       = require "lib.unity_engine"
local GameObject        = UnityEngine.GameObject
local MeshFilter        = UnityEngine.MeshFilter
local Resources         = UnityEngine.Resources
local Mesh              = UnityEngine.Mesh
local Vector3           = UnityEngine.Vector3
local MeshRenderer      = UnityEngine.MeshRenderer
local Material          = UnityEngine.Material

local function awake()
    print("---- awake ----")
end

local function start()
    print("---- start ----")
    SceneMgr.init_scene()
end

local function update()
    InputControl.update_input()
end

local function late_update()
end

local function fixed_update()
end

return {
    awake           = awake,
    start           = start,
    update          = update,
    late_update     = late_update,
    fixed_update    = fixed_update,
}

input_control.lua

local SceneMgr      = require "logic.scene_mgr"

local UnityEngine   = require "lib.unity_engine"
local Input         = UnityEngine.Input
local x = 0
local y = 0

local function update_input()
    -- print( "vertical: ",   Input.GetAxis("Vertical") )
    -- print( "horizontal: ", Input.GetAxis("Horizontal") )
    local scene = SceneMgr.get_scene()
    x = x + Input.GetAxis("Horizontal") * 50
    y = y + Input.GetAxis("Vertical") * 50
    scene.hero:move( x, y )
end

local function start()
end

return {
    update_input = update_input,
	start = start,
}

scene_mgr.lua

local Hero = require "sprite.hero"

local Scene

local function create_hero()
    return Hero.create()
end

local function init_scene()
    Scene = {}
    Scene.hero = create_hero()
    return Scene
end

local function get_scene()
    return Scene
end

return {
    init_scene = init_scene,
    get_scene  = get_scene,
}

hero.lua

local UnityEngine       = require "lib.unity_engine"
local GameObject        = UnityEngine.GameObject
local MeshFilter        = UnityEngine.MeshFilter
local Resources         = UnityEngine.Resources
local Mesh              = UnityEngine.Mesh
local Vector3           = UnityEngine.Vector3
local MeshRenderer      = UnityEngine.MeshRenderer
local Material          = UnityEngine.Material

local function create()
	
	
	local Test = GameObject._New("Test")
	
	
    local component
    local mesh = Resources.Load("Mesh/Quad1x1W1L1VC", Mesh._Type())
    local material = Resources.Load("Material/Sprite", Material._Type())
    local unity_obj = GameObject._New("HERO")
    component = unity_obj:AddComponent(MeshFilter._Type())
    local mesh_filter = MeshFilter._ConvertFrom(component)
    print("mesh_filter:", mesh_filter:ToString())
    print("mesh_filter.mesh:", mesh_filter.mesh)
    mesh_filter.sharedMesh = Mesh._ConvertFrom(mesh)
    unity_obj.transform.localScale = Vector3._New(128,128,128)

    component = unity_obj:AddComponent(MeshRenderer._Type())
    local mesh_renderer = MeshRenderer._ConvertFrom(component)
    mesh_renderer.castShadows = false
    mesh_renderer.receiveShadows = false
    mesh_renderer.material = Material._ConvertFrom(material)

    local mt = {
        __index = {
            move = function(self, x, y)
                local unity_obj = rawget(self, "__unity_obj")
                unity_obj.transform.localPosition = Vector3._New(x, y, 0)
            end
        },
        __newindex = function(self, key, value)
        end,
    }
    return setmetatable({
        __unity_obj = unity_obj,
    }, mt)
end

return {
    create = create,
}

项目地址 https://github.com/xebecnan/UniLua

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值