L04.实战 /images/wallhaven-7ple5y.jpg

1.lua实现生命周期

Bootstrap.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

//lua生命周期
public delegate void LifeCycle();

//将Lua与Lua核心表对应的结构体
[GCOptimize]
public struct LuaBootstrap
{
public LifeCycle Start;
public LifeCycle Update;
public LifeCycle OnDestroy;
}

public class Bootstrap : MonoBehaviour
{
//Lua的核心table
private LuaBootstrap _Bootstrap;

//调用起Lua代码
void Start()
{
//防止切换场景时,脚本对象丢失
DontDestroyOnLoad(gameObject);

xLuaEnv.Instance.DoString("require('Bootstrap')");

//将Lua的核心table,导入到C#端
_Bootstrap = xLuaEnv.Instance.Global.Get<LuaBootstrap>("Bootstrap");
//lua start
_Bootstrap.Start();
}

void Update()
{
//luaupdate
_Bootstrap.Update();
}

//释放Lua的代码
void OnDestroy()
{
//lua OnDestroy
_Bootstrap.OnDestroy();

//释放Lua环境前,需要将导出到C#的Lua回调函数进行释放
_Bootstrap.Start = null;
_Bootstrap.Update = null;
_Bootstrap.OnDestroy = null;

xLuaEnv.Instance.Free();
}
}

Bootstrap.lua

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Bootstrap = {}

--核心table,存储所有的控制器
Bootstrap.Controllers = {}

Bootstrap.Start = function()
Bootstrap.LoadPage("MainMenuController")
end

Bootstrap.Update = function()
print("Lua Update")
end

Bootstrap.OnDestroy = function()
print("Lua OnDestroy")
end

2.lua MVC