U3DScripting

LuaBehaviour.cs

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using XLua;
  5. using System;
  6. [System.Serializable]
  7. public class Injection
  8. {
  9. public string name;
  10. public GameObject value;
  11. }
  12. [LuaCallCSharp]
  13. public class LuaBehaviour : MonoBehaviour {
  14. public TextAsset luaScript;
  15. public Injection[] injections;
  16. internal static LuaEnv luaEnv = new LuaEnv(); //all lua behaviour shared one luaenv only!
  17. internal static float lastGCTime = 0;
  18. internal const float GCInterval = 1;//1 second
  19. private Action luaStart;
  20. private Action luaUpdate;
  21. private Action luaOnDestroy;
  22. private LuaTable scriptEnv;
  23. void Awake()
  24. {
  25. scriptEnv = luaEnv.NewTable();
  26. LuaTable meta = luaEnv.NewTable();
  27. meta.Set("__index", luaEnv.Global);
  28. scriptEnv.SetMetaTable(meta);
  29. meta.Dispose();
  30. scriptEnv.Set("self", this);
  31. foreach (var injection in injections)
  32. {
  33. scriptEnv.Set(injection.name, injection.value);
  34. }
  35. luaEnv.DoString(luaScript.text, "LuaBehaviour", scriptEnv);
  36. Action luaAwake = scriptEnv.Get<Action>("awake");
  37. scriptEnv.Get("start", out luaStart);
  38. scriptEnv.Get("update", out luaUpdate);
  39. scriptEnv.Get("ondestroy", out luaOnDestroy);
  40. if (luaAwake != null)
  41. {
  42. luaAwake();
  43. }
  44. }
  45. // Use this for initialization
  46. void Start ()
  47. {
  48. if (luaStart != null)
  49. {
  50. luaStart();
  51. }
  52. }
  53. // Update is called once per frame
  54. void Update ()
  55. {
  56. if (luaUpdate != null)
  57. {
  58. luaUpdate();
  59. }
  60. if (Time.time - LuaBehaviour.lastGCTime > GCInterval)
  61. {
  62. luaEnv.Tick();
  63. LuaBehaviour.lastGCTime = Time.time;
  64. }
  65. }
  66. void OnDestroy()
  67. {
  68. if (luaOnDestroy != null)
  69. {
  70. luaOnDestroy();
  71. }
  72. luaOnDestroy = null;
  73. luaUpdate = null;
  74. luaStart = null;
  75. scriptEnv.Dispose();
  76. injections = null;
  77. }
  78. }

LuaTestScript.lua.txt

  1. local speed = 10
  2. function start()
  3. print("lua start...")
  4. end
  5. function update()
  6. local r = CS.UnityEngine.Vector3.up * CS.UnityEngine.Time.deltaTime * speed
  7. self.transform:Rotate(r)
  8. end
  9. function ondestroy()
  10. print("lua destroy")
  11. end

?