CoroutineHelper.lua.txt 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. local XLuaUtil = require("XLua/util.lua")
  2. local CoroutineHelper = {}
  3. CoroutineHelper._CS_SCoroutineRunner_Component = nil
  4. -- Just give a lua function.
  5. -- You can call like this: coroutine.yield(CS.UnityEngine.WaitForSeconds(3))
  6. -- Or you can call CoroutineHelper.Wait(3) for short.
  7. function CoroutineHelper:Start(...)
  8. print("CoroutineHelper.Start ... ... ")
  9. local luaRoot = CS.UnityEngine.GameObject.Find("LuaRoot")
  10. assert(luaRoot ~= nil)
  11. local coroutineHolder = luaRoot.transform:Find("coroutineHolder")
  12. if not coroutineHolder then
  13. coroutineHolder = CS.UnityEngine.GameObject("coroutineHolder")
  14. coroutineHolder.transform:SetParent(luaRoot.transform)
  15. self._CS_SCoroutineRunner_Component = coroutineHolder:AddComponent(typeof(CS.SFramework.SCoroutineRunner))
  16. end
  17. assert(CoroutineHelper._CS_SCoroutineRunner_Component ~= nil, "SCoroutineRunner is not exised!")
  18. return CoroutineHelper._CS_SCoroutineRunner_Component:StartCoroutine(XLuaUtil.cs_generator(...))
  19. end
  20. function CoroutineHelper:Stop(targetCoroutine)
  21. print("CoroutineHelper.Stop ... ... ")
  22. assert(self._CS_SCoroutineRunner_Component ~= nil, "SCoroutineRunner is not exised!")
  23. if targetCoroutine then
  24. self._CS_SCoroutineRunner_Component:StopCoroutine(targetCoroutine)
  25. end
  26. end
  27. function CoroutineHelper:CoroutineCall(func)
  28. return function(...)
  29. local co = coroutine.create(func)
  30. assert(coroutine.resume(co, ...))
  31. end
  32. end
  33. function CoroutineHelper:Wait(seconds)
  34. coroutine.yield(CS.UnityEngine.WaitForSeconds(seconds))
  35. end
  36. function CoroutineHelper:WaitForEndOfFrame()
  37. coroutine.yield(CS.UnityEngine.WaitForEndOfFrame())
  38. end
  39. function CoroutineHelper:Test()
  40. local targetCoroutine = CoroutineHelper.Start(
  41. function()
  42. print("Test Co a Start ... ...")
  43. coroutine.yield(CoroutineHelper.Start(function()
  44. print("Test Co b started inside coroutine a")
  45. coroutine.yield(CS.UnityEngine.WaitForSeconds(2))
  46. print("Co b Run in Co a")
  47. end))
  48. while true do
  49. coroutine.yield(CS.UnityEngine.WaitForSeconds(1))
  50. print("Test Co a alive ... ...")
  51. end
  52. end
  53. )
  54. CoroutineHelper.Start(
  55. function()
  56. print("Test Co c Start ... ... close Co a after 8 seconds")
  57. coroutine.yield(CS.UnityEngine.WaitForSeconds(8))
  58. CoroutineHelper.Stop(targetCoroutine)
  59. print("Close Co a By Co c ... ...")
  60. end
  61. )
  62. end
  63. return CoroutineHelper