using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;
[System.Serializable]
public class Injection
{
public string name;
public GameObject value;
}
[LuaCallCSharp]
public class LuaBehaviour : MonoBehaviour {
public TextAsset luaScript;
public Injection[] injections;
internal static LuaEnv luaEnv = new LuaEnv(); //all lua behaviour shared one luaenv only!
internal static float lastGCTime = 0;
internal const float GCInterval = 1;//1 second
private Action luaStart;
private Action luaUpdate;
private Action luaOnDestroy;
private LuaFun luaTest;
private LuaTable scriptEnv;
void Awake()
{
scriptEnv = luaEnv.NewTable();
LuaTable meta = luaEnv.NewTable();
meta.Set("__index", luaEnv.Global);
//设置meta为scriptEnv的元表
scriptEnv.SetMetaTable(meta);
meta.Dispose();
scriptEnv.Set("self", this);
foreach (var injection in injections)
{
scriptEnv.Set(injection.name, injection.value);
}
//加载lua代码到scriptEnv中
luaEnv.DoString(luaScript.text, "LuaBehaviour", scriptEnv);
//获取一个全局的awake方法映射到delegate这里用的是Action
Action luaAwake = scriptEnv.Get<Action>("awake");
//自己测试自定义delegate
//luaTest = scriptEnv.Get<LuaFun>("start");
// luaStart = scriptEnv.Get<Action>("start");
// luaUpdate = scriptEnv.Get<Action>("update");
// luaOnDestroy = scriptEnv.Get<Action>("ondestroy");
scriptEnv.Get("start", out luaStart);
scriptEnv.Get("update", out luaUpdate);
scriptEnv.Get("ondestroy", out luaOnDestroy);
if (luaAwake != null)
{
luaAwake();
}
}
public delegate void LuaFun();
// Use this for initialization
void Start ()
{
if (luaStart != null)
{
luaStart();
}
}
// Update is called once per frame
void Update ()
{
if (luaUpdate != null)
{
luaUpdate();
}
// 清除Lua的未手动释放的LuaBase(比如,LuaTable, LuaFunction),以及其它一些事情。
if (Time.time - LuaBehaviour.lastGCTime > GCInterval)
{
luaEnv.Tick();
LuaBehaviour.lastGCTime = Time.time;
}
}
void OnDestroy()
{
if (luaOnDestroy != null)
{
luaOnDestroy();
}
luaOnDestroy = null;
luaUpdate = null;
luaStart = null;
scriptEnv.Dispose();
injections = null;
}
}
- lua代码
local speed = 10
function start()
print("lua start...")
end
function update()
local r = CS.UnityEngine.Vector3.up * CS.UnityEngine.Time.deltaTime * speed
self.transform:Rotate(r)
end
function ondestroy()
print("lua destroy")
end
在lua中调用成员方法的时候使用冒号
local cameracom = camera:GetComponent(“Camera”);
调用静态方法的时候通过类似于下面方式
local camera = gameObject.Find(“Main Camera”)
获取对象
local gameObject = CS.UnityEngine.GameObject