XLua和C#互调的一个简单案例
用Lua写了一个点击旋转的方法,可以先把这三个脚本拖进去看看效果。
C#脚本如下:
1.一个Lua虚拟机单例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
/// <summary>
/// Lua虚拟机单例模板
/// </summary>
public class LuaSimulator : MonoBehaviour
{
internal static float lastGcTime = 0;
public const float gcInterval = 1;//释放内存的间隔时间
static LuaEnv myLuaEnv;
public static LuaEnv MyLuaEnv
{
get
{
if (myLuaEnv == null)
{
myLuaEnv = new LuaEnv();
}
return myLuaEnv;
}
}
void Update()
{
if (Time.time - lastGcTime > gcInterval)
{
myLuaEnv.Tick();
lastGcTime = Time.time;
}
}
}
2.CSCallLua
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System;
public class MBehaviour : MonoBehaviour {
public TextAsset luaScript;
private Action luaAwake;
private Action luaStart;
private Action luaUpdate;
private Action<Collider> luaOnTriggerEnter;
private Action luaOnDestroy;
private LuaTable scriptEnv;
void Awake()
{
scriptEnv = LuaSimulator.MyLuaEnv.NewTable();
// 为每个脚本设置一个独立的环境,可一定程度上防止脚本间全局变量、函数冲突
LuaTable meta = LuaSimulator.MyLuaEnv.NewTable();
meta.Set("__index", LuaSimulator.MyLuaEnv.Global);
scriptEnv.SetMetaTable(meta);
meta.Dispose();
scriptEnv.Set("self", this);
LuaSimulator.MyLuaEnv.DoString(luaScript.text,"ChunkName",scriptEnv);//ChunkName是什么无所谓
scriptEnv.Get("Awake", out luaAwake);
scriptEnv.Get("Start", out luaStart);
scriptEnv.Get("Update", out luaUpdate);
scriptEnv.Get("OnTriggerEnter", out luaOnTriggerEnter);
scriptEnv.Get("OnDestroy", out luaOnDestroy);
if (luaAwake != null)
{
luaAwake();
}
DontDestroyOnLoad(gameObject);
}
void Start () {
if (luaStart != null)
{
luaStart();
}
}
// Update is called once per frame
void Update () {
if (luaUpdate != null)
{
luaUpdate();
}
}
void OnTriggerEnter(Collider other)
{
if (luaOnTriggerEnter != null)
{
luaOnTriggerEnter(other);
}
}
void OnDestroy()
{
if (luaOnDestroy != null)
{
luaOnDestroy();
}
luaOnDestroy = null;
luaUpdate = null;
luaStart = null;
luaAwake = null;
scriptEnv.Dispose();
}
}
3.LuaCallCS对应的Lua脚本如下,文件后缀名为.lua.txt或者.txt,但是不能为.lua,Unity不能直接识别.lua后缀名的文件,一般习惯性后缀名都使用.lua.txt,以便于区分脚本文件类型,脚本名字的话随便起。
Debug = CS.UnityEngine.Debug
Input = CS.UnityEngine.Input
GameObject = CS.UnityEngine.GameObject
Vector3 = CS.UnityEngine.Vector3
function Awake()
Debug.Log("你好,我是Lua的Awake方法")
end
function Start()
Debug.Log("你好,我是Lua的Start方法")
end
function Update()
--Debug.Log("你好,我是Lua的Update方法")
GameObjectRotate()
end
function OnDestroy()
Debug.Log("你好,我是Lua的OnDestroy方法")
end
function GameObjectRotate()
if (Input.GetMouseButton(0)) then
GameObject.Find("Cube").transform:Rotate(Vector3.up, 30);
Debug.Log("你好,我是Lua的GameObjectRotate方法")
end
end