using UnityEngine;
|
using System.Collections;
|
using System.Collections.Generic;
|
using XLua;
|
using System;
|
using System.IO;
|
|
[System.Serializable]
|
public class Injection
|
{
|
public string name;
|
public GameObject value;
|
}
|
|
[LuaCallCSharp]
|
public class LuaBehaviour : MonoBehaviour
|
{
|
public string fileName;
|
public Injection[] injections;
|
|
private Action luaStart;
|
private Action luaUpdate;
|
private Action luaOnDestroy;
|
|
private LuaTable scriptEnv;
|
|
void Awake()
|
{
|
scriptEnv = LuaUtility.env.NewTable();
|
|
// 为每个脚本设置一个独立的环境,可一定程度上防止脚本间全局变量、函数冲突
|
LuaTable meta = LuaUtility.env.NewTable();
|
meta.Set("__index", LuaUtility.env.Global);
|
scriptEnv.SetMetaTable(meta);
|
meta.Dispose();
|
|
scriptEnv.Set("self", this);
|
foreach (var injection in injections)
|
{
|
scriptEnv.Set(injection.name, injection.value);
|
}
|
|
LuaUtility.Do(fileName, "LuaBehaviour", scriptEnv);
|
|
Action luaAwake = scriptEnv.Get<Action>("Awake");
|
scriptEnv.Get("Start", out luaStart);
|
scriptEnv.Get("Update", out luaUpdate);
|
scriptEnv.Get("OnDestroy", out luaOnDestroy);
|
|
if (luaAwake != null)
|
{
|
luaAwake();
|
}
|
}
|
|
void Start()
|
{
|
if (luaStart != null)
|
{
|
luaStart();
|
}
|
}
|
|
void Update()
|
{
|
if (luaUpdate != null)
|
{
|
luaUpdate();
|
}
|
}
|
|
void OnDestroy()
|
{
|
if (luaOnDestroy != null)
|
{
|
luaOnDestroy();
|
}
|
luaOnDestroy = null;
|
luaUpdate = null;
|
luaStart = null;
|
scriptEnv.Dispose();
|
injections = null;
|
}
|
}
|