Guest User

system.lua

a guest
Aug 26th, 2019
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.05 KB | None | 0 0
  1. -- Services
  2. local replicatedStorage = game:GetService("ReplicatedStorage")
  3.  
  4. local shared = replicatedStorage.shared
  5.  
  6. local sharedLib = shared.lib
  7. local signalLib = require(sharedLib.signalLib)
  8.  
  9. local sharedData = shared.data
  10. local entityPool = require(sharedData.entityPool)
  11.  
  12. local system = {}
  13. system.__index = system
  14.  
  15. function system.new(componentName)
  16.     local systemPool = entityPool.componentEntityMap[componentName] or {}
  17.     entityPool.componentEntityMap[componentName] = systemPool
  18.  
  19.     -- Base system intentionally lacks a default update() member
  20.     local self = setmetatable({}, system)
  21.     self.registeredEntityCount = 0
  22.     self.pool = systemPool
  23.  
  24.     signalLib.subscribeAsync("componentAttached", function(attachedComponentName, entityId)
  25.         if attachedComponentName == componentName then
  26.             self:onEntityRegistered(entityId)
  27.         end
  28.     end)
  29.     signalLib.subscribeAsync("componentDetached", function(detachedComponentName, entityId)
  30.         if detachedComponentName == componentName then
  31.             self:onEntityRegistered(entityId)
  32.         end
  33.     end)
  34.     -- Allows for communication between systems
  35.     signalLib.subscribeAsync("entitySignal", function(component, entityId, ...)
  36.         if component == componentName and self.onEntitySignal then
  37.             self:onEntitySignal(entityId, ...)
  38.         end
  39.     end)
  40.  
  41.     return self
  42. end
  43.  
  44. -- Called implicitly by entityPool's addComponent function.
  45. function system:onEntityRegistered(entityId)
  46.     self.registeredEntityCount = self.registeredEntityCount + 1
  47.  
  48.     -- Calls inhereted class' entity registered callback if it has one.
  49.     if self._onEntityRegistered then
  50.         self:_onEntityRegistered(entityId)
  51.     end
  52.  
  53.     return entityId
  54. end
  55.  
  56. -- Called implicitly by entityPool's removeComponent function.
  57. function system:onEntityDeregistered(entityId)
  58.     -- Guard clause not needed, the entity is checked for its existence in entityPool.
  59.     self.registeredEntityCount = self.registeredEntityCount - 1
  60.  
  61.     -- Calls inhereted class' entity registered callback if it has one.
  62.     if self["_onEntityDeregistered"] then
  63.         self:_onEntityDeregistered(entityId)
  64.     end
  65. end
  66.  
  67. return system
Add Comment
Please, Sign In to add comment