StepDispatcher.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. -- Tells other modules to update automagically, so you dont have to connect to Stepped.
  2. local RunService = game:GetService("RunService")
  3. local StepDispatcher = {}
  4. local ModuleManager = nil
  5. local Last = tick()
  6. local Now = tick()
  7. local Elapsed = 0
  8. local Delta = 0
  9. local function IsFunction(x)
  10. return (type(x) == "function")
  11. end
  12. -- pcall this method and output if any errors occor. This is done so
  13. -- that one module erroring doesn't bring everything crashing down.
  14. local function SafeCallMethod(module,methodname, ...)
  15. if IsFunction(module[methodname]) then
  16. local Success, Msg = pcall(module[methodname], module, ...)
  17. if not Success then
  18. warn(Msg)
  19. end
  20. end
  21. end
  22. local function StepModules(modules,elapsed,dt)
  23. for _,module in pairs(modules) do
  24. SafeCallMethod(module,"PreStep",elapsed,dt)
  25. SafeCallMethod(module,"Step",elapsed,dt)
  26. SafeCallMethod(module,"PostStep",elapsed,dt)
  27. end
  28. end
  29. local function RenderStepModules(modules)
  30. Now = tick()
  31. Delta = Now-Last
  32. Elapsed = Elapsed + Delta
  33. for _,module in pairs(modules) do
  34. SafeCallMethod(module, "RenderStep", Elapsed, Delta)
  35. end
  36. Last = Now
  37. end
  38. function StepDispatcher:Init(moduleManager)
  39. ModuleManager = moduleManager
  40. end
  41. function StepDispatcher:Start()
  42. local Modules = ModuleManager:GetModules()
  43. RunService.Stepped:Connect(function(elapsed,delta)
  44. StepModules(Modules,elapsed,delta)
  45. end)
  46. if RunService:IsClient() then
  47. RunService:BindToRenderStep("StepDispatcherRenderStep",Enum.RenderPriority.First.Value,function()
  48. RenderStepModules(Modules)
  49. end)
  50. end
  51. end
  52. return StepDispatcher