How to make DataStores sync over multiple places in the same game?

Hello. I’ve recently been trying to make data save using a datastore, which I usually can do without issue. The issue came when I wanted it to synchronise over all of the places linked to the game.

The datastore saves data in the leaderboard and I’ve posted my script below. I made this script and I know for a fact that it works in games with single start places, but I’m unsure how to get it to sync over all places in a universe.

I want it to update over all places when a player leaves, not just save it in that one place but save in all the other places also. I was wondering how to do it and if it’s even possible.

The main thing I want to find out is how to get data from all places in a universe to synchronise over all games, so for example if I gave myself 10 points in one place, it saves my 10 points in all the other places.

local DataStoreService = game:GetService("DataStoreService")

local PointsDataStore = DataStoreService:GetDataStore("PointsData")

game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = plr
	
	local rank = Instance.new("StringValue")
	rank.Name = "Rank"
	rank.Value = plr:GetRoleInGroup(3272666)
	rank.Parent = leaderstats
	
	local points = Instance.new("IntValue")
	points.Name = "Points"
	points.Parent = leaderstats
	
	
	local data
	local success, errormessage = pcall(function()
		data = PointsDataStore:GetAsync(plr.UserId.."-points") 
	end)
	if success then
		points.Value = data
	else
		print("There was an error getting player data. Player data not loaded.")
		warn(errormessage)
	end
	
end)

game.Players.PlayerRemoving:Connect(function(plr)
	
	local success, errormessage = pcall(function()
		PointsDataStore:SetAsync(plr.UserId.."-points",plr.leaderstats.Miles.Value)
	end)
	
	
	if success then
		print("Player data was saved successfully.")
	else
		print("There was an error saving player data.")
		warn(errormessage)
	end
end)

Thanks,
LegendOJ1.

1 Like

DataStores carry across all places in a game by default. You should already be able to do this with your code assuming it is not broken otherwise.

6 Likes

Would I have to copy and paste the script into all places in order to make this work or would I just put my script in the game’s start place?

2 Likes

Yes, you need to put the script into any game that will be using the data. On another note, I recommend looking into the DataStore UpdateAsync function over SetAsync to avoid issues relating to caching.

3 Likes

Alright, I’ll have a look into UpdateAsync. Thanks for the advice.

1 Like