Unity实验室之C#调用Lua脚本

作者: koo叔 分类: Unity3D 发布时间: 2018-04-19 23:26 编辑

介绍

xLua是腾讯在github上的一个开源项目(下载链接),主要解决热更的问题,是和C#(Unity,.Net,Mono)结合的解决方案。支持android,ios,windows,linux,osx等平台。目前已经有许多成熟产品应用案例使用了xLua.本文主要介绍C#如何调用xLua脚本。

变量

-- example.lua.txt
id=25
name='hello'
isMale = true
//Example.cs
var id = luaenv.Global.Get<int>("id");
var name = luaenv.Global.Get<string>("name");
var isMale = luaenv.Global.Get<bool>("isMale");
Debug.Log(id);
Debug.Log(name);
Debug.Log(isMale);

调用类的实例

--example.lua.txt
character={
    m_id=25,
    m_name='hello'
}
//Example.cs
public class Character{
    public int m_id;
    public string m_name;
}
var character = luaenv.Global.Get<Character>("character");
Debug.Log(character.m_id);
Debug.Log(character.m_name);

调用列表

-- example.lua.txt
character={
    5,10,15
}
//Example.cs
var character = luaenv.Global.Get<List<int>>("character");
Debug.Log(character[0]);
Debug.Log(character[1]);
Debug.Log(character[2]);
Debug.Log(character.Count);

调用接口

--example.lua.txt
character = {
    Id = 25,
    Name='hello',
    Add = function(self,a,b)
        print('Character.Add')
        return a+b
        end
}
//Example.cs
using XLua;
[CSharpCallLua]
public interface ICharacter{
    int Id{get;set;}
    string Name{get;set;}
    int Add(int a,int b);
}
var character = luaenv.Global.Get<ICharacter>("character");
Debug.Log(character.Id);
Debug.Log(character.Name);
Debug.Log(character.Add(5,10));

LuaTable

--example.lua.txt
character={
    m_id=25,
    m_name='hello'
}
//Example.cs
var character = luaenv.Global.Get<LuaTable>("character")
Debug.Log(character.Get<int>("m_id"));
Debug.Log(character.Get<string>("m_name"));

函数调用

--example.lua.txt
function Log()
    print('hello')
end
//Example.cs
using System;
var log = luaenv.Global.Get<Action>("Log");
log();
log = null;

复杂函数

--example.lua.txt
function Battle(id,name)
    print(id,name)
    return "success",{m_coin=512,m_exp=1024}
end
//Example.cs
using XLua;
public class Result{
    public int m_coin;
    public int m_exp;
}
[CSharpCallLua]
public delegate string Battle(int id,string name,out Result c);
var func = luaenv.Global.Get<Battle>("Battle");
Result result;
var message = func(25,'hello',out result);
func = null;
Debug.Log(message);
Debug.Log(result.m_coin);
Debug.Log(result.m_exp);

代理

--example.lua.txt
function ShowMessage()
    print('5 hello!')
end
function Attack()
    print('attack')
    return ShowMessage
end
//Example.cs
using XLua;
[CSharpCallLua]
public delegate Action Attack();
var attack = luaenv.Global.Get<Attack>("Attack");
var showMessage = attack();
showMessage();
attack = null;
showMessage = null;

LuaFunction

--example.lua.txt
function ShowMessage()
    print('hello')
end
//Example.cs
using XLua;
var showMessage = luaenv.Global.Get<LuaFunction>("ShowMessage");
showMessage.Call();

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

你的email不会被公开。必填项已用*标注

更多阅读
标签云