本篇文章主要介绍lua与C#代码之间的互访以及C#的常用组件Behaviour脚本周期函数的Lua版封装的实现。
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;
/*
* Author:W
* Lua与C#代码之间的相互访问
* Lua版的MonoBehaviour脚本生命周期函数封装
*
*/
public class LuaBehaviourTest : MonoBehaviour {
public TextAsset myLuaBehaviour;
private LuaEnv luaEnv = new LuaEnv();
private LuaTable luaScriptEnv;
private Action luaAwake;
private Action luaStart;
private Action luaOnEnable;
private Action luaOnDisable;
private Action luaUpdate;
private Action luaOnDestroy;
void Awake()
{
luaEnv = new LuaEnv();
//1.为新建的NewTable设置原表:luaEnv.Global
luaScriptEnv = luaEnv.NewTable();
// 为每个脚本设置一个独立的环境,可一定程度上防止脚本间全局变量、函数冲突
LuaTable meta = luaEnv.NewTable();
meta.Set("__index", luaEnv.Global);
luaScriptEnv.SetMetaTable(meta);
meta.Dispose();
//2.【重点】把C#游戏对象映射到对应MyLua文件中供访问
luaScriptEnv.Set("self",this);
luaEnv.DoString(myLuaBehaviour.text, "MyLua",luaScriptEnv);
luaAwake = luaScriptEnv.Get<Action>("Awake");
luaStart = luaScriptEnv.Get<Action>("Start");
luaOnEnable = luaScriptEnv.Get<Action>("OnEnable");
luaOnDisable = luaScriptEnv.Get<Action>("OnDisable");
luaUpdate = luaScriptEnv.Get<Action>("Update");
luaOnDestroy = luaScriptEnv.Get<Action>("OnDestroy");
if (luaAwake != null)
luaAwake();
}
void OnEnable()
{
if (luaOnEnable != null)
luaOnEnable();
}
void OnDisable()
{
if (luaOnDisable != null)
luaOnDisable();
}
// Use this for initialization
void Start () {
if (luaStart != null)
luaStart();
}
// Update is called once per frame
void Update () {
if (luaUpdate != null)
luaUpdate();
}
void OnDestroy()
{
if (luaOnDestroy != null)
luaOnDestroy();
luaAwake = null;
luaStart = null;
luaOnEnable = null;
luaOnDisable = null;
luaUpdate = null;
luaOnDestroy = null;
luaScriptEnv.Dispose();
luaEnv.Dispose();
}
#region 【测试】供Lua访问的变量与函数
public int num = 0;
public void Test()
{
Debug.LogError("Test");
}
#endregion
}
lua文件如下
function Awake()
print("====Lua Awake====");
end
function Start()
print("====Lua Start====");
print("======Lua Init===="..self.num);
self:Test();
end
function OnEnable()
print("====Lua OnEnable====");
end
function OnDisable()
print("====Lua OnDisable====");
end
function Update()
print("====Lua Update====");
end
function OnDestroy()
print("====Lua OnDestroy====");
end
运行结果如下