Replica - Server to client state replication (Module)

As per ReplicaService documentation for tokens:

Tokens are meant to be identifiers for a collection of replicas, not for the individual objects they’re representing. The idea was that there might be cases where multiple people might be working on the same project and may end up using identical identifiers for player or other data - tokens completely prevent this from happening.

It might’ve been my mistake only providing examples where the Token is created wrapped inside the Replica creation function - In a lot of cases you’d actually need to define the token outside of Replica creation and store a reference to that token so you could create multiple Replicas with the same token.

You can additionally identify a Replica to represent a Player by storing an identifier in:

  • .Tags - e.g. Tags = {UserId = 2312310, ...} - This is preferable, because Tags becomes immutable after a Replica is created. Tags was specifically made for storing identifiers like that.
  • .Data - e.g. Data = {UserId = 2312310, ...}

Example:

-- Server
local Token = Replica.Token("PlayerData")

...

local replica = Replica.New({
   Token = Token,
   Tags = {UserId = player.UserId},
   Data = {},
})
replica:Subscribe(player)
-- Client
Replica.OnNew("PlayerData", function(replica)
   if replica.Tags.UserId == game.Players.LocalPlayer.UserId then
      -- This replica is representing local player's data
   end
end)

(In addition you can skip the replica.Tags.UserId == game.Players.LocalPlayer.UserId check if you’re only ever replicating a single “PlayerData” replica to a single player who’s also the owner of that data. There might still be cases where you might want to replicate everyone’s data to everyone)

5 Likes