Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local ReplicatedStorage = game:GetService("ReplicatedStorage")
- local Components = require(ReplicatedStorage.Shared.Components)
- local remoteEvent = ReplicatedStorage:WaitForChild("MatterRemote")
- local function SetupReplication(world, state)
- local function debugPrint(...)
- if state.debugEnabled then
- print("Replication>", ...)
- end
- end
- remoteEvent.OnClientEvent:Connect(function(entities)
- for entityId, componentMap in entities do
- local entityId = tonumber(entityId)
- local exists = world:contains(entityId)
- if exists and next(componentMap) == nil then
- world:despawn(entityId)
- debugPrint(string.format("Despawn %s", entityId))
- continue
- end
- local componentsToInsert = {}
- local componentsToRemove = {}
- local insertNames = {}
- local removeNames = {}
- for name, container in componentMap do
- if container.data then
- table.insert(componentsToInsert, Components[name](container.data))
- table.insert(insertNames, name)
- else
- table.insert(componentsToRemove, Components[name])
- table.insert(removeNames, name)
- end
- end
- if not exists then
- -- the "NonShared" is used for shared systems that run on both sides
- -- by filtering out by default entities that were created on the server and replicated to the client
- -- which leads to shared systems running for the entity on the same side they were created on
- -- an example of a shared system is a system of mine that handles checking collisions
- -- by doing the same calculations each frame and storing the results which are a table of ids
- -- in a component, which would have been hard to do because of how ids are not the same on
- -- both sides so entities created on the server would have replicated false ids compared to the client
- -- but thanks to this change they work well
- world:spawnAt(entityId, Components.NonShared(), unpack(componentsToInsert))
- debugPrint(
- string.format("Spawn %s with %s", entityId, table.concat(insertNames, ","))
- )
- else
- if #componentsToInsert > 0 then
- world:insert(entityId, unpack(componentsToInsert))
- end
- if #componentsToRemove > 0 then
- world:remove(entityId, unpack(componentsToRemove))
- end
- debugPrint(
- string.format(
- "Modify %s adding %s, removing %s",
- entityId,
- if #insertNames > 0 then table.concat(insertNames, ", ") else "nothing",
- if #removeNames > 0 then table.concat(removeNames, ", ") else "nothing"
- )
- )
- end
- end
- end)
- end
- return SetupReplication
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement