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