少年修仙传客户端基础资源
Leonard Wu
2018-08-15 a24a563bf87176211b80aa0bb1642c8b5b731f89
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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;
    }
}