SLuaBehaviour.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. //using XLua;
  5. //using System;
  6. namespace SFramework
  7. {
  8. [System.Serializable]
  9. public class Injection
  10. {
  11. public string name;
  12. public GameObject value;
  13. }
  14. [XLua.LuaCallCSharp]
  15. public class SLuaBehaviour : MonoBehaviour
  16. {
  17. public TextAsset luaScript;
  18. public Injection[] injections;
  19. //internal static XLua.LuaEnv luaEnv = new XLua.LuaEnv(); //all lua behaviour shared one luaenv only!
  20. internal static XLua.LuaEnv luaEnv = SLuaEnv.Instance;
  21. internal static float lastGCTime = 0;
  22. internal const float GCInterval = 1;//1 second
  23. private System.Action _luaStart;
  24. private System.Action _luaUpdate;
  25. private System.Action _luaOnDestroy;
  26. private XLua.LuaTable _scriptEnv;
  27. void Awake()
  28. {
  29. _scriptEnv = luaEnv.NewTable();
  30. // 为每个脚本设置一个独立的环境,可一定程度上防止脚本间全局变量、函数冲突
  31. XLua.LuaTable meta = luaEnv.NewTable();
  32. meta.Set("__index", luaEnv.Global);
  33. _scriptEnv.SetMetaTable(meta);
  34. meta.Dispose();
  35. _scriptEnv.Set("self", this);
  36. foreach (var injection in injections)
  37. {
  38. _scriptEnv.Set(injection.name, injection.value);
  39. }
  40. luaEnv.DoString(luaScript.text, "LuaBehaviour", _scriptEnv);
  41. System.Action luaAwake = _scriptEnv.Get<System.Action>("Awake");
  42. _scriptEnv.Get("Start", out _luaStart);
  43. _scriptEnv.Get("Update", out _luaUpdate);
  44. _scriptEnv.Get("OnDestroy", out _luaOnDestroy);
  45. if (luaAwake != null)
  46. {
  47. luaAwake();
  48. }
  49. }
  50. // Use this for initialization
  51. void Start()
  52. {
  53. if (_luaStart != null)
  54. {
  55. _luaStart();
  56. }
  57. }
  58. // Update is called once per frame
  59. void Update()
  60. {
  61. if (_luaUpdate != null)
  62. {
  63. _luaUpdate();
  64. }
  65. if (Time.time - SLuaBehaviour.lastGCTime > GCInterval)
  66. {
  67. luaEnv.Tick();
  68. SLuaBehaviour.lastGCTime = Time.time;
  69. }
  70. }
  71. void OnDestroy()
  72. {
  73. if (_luaOnDestroy != null)
  74. {
  75. _luaOnDestroy();
  76. }
  77. _luaOnDestroy = null;
  78. _luaUpdate = null;
  79. _luaStart = null;
  80. _scriptEnv.Dispose();
  81. injections = null;
  82. }
  83. }
  84. }