So I made a game. The game is basically just 2 parts. and the leaderboard has “Points” And “Xp” and it is obvious what do those 2 parts do. They give you points AND ALSO XP. But if I leave and rejoin, they are not saved.
The script that I used to make the leaderstats was a script that waits for the player until they join, creates a new leaderstats file, and the values. But I want a script that not just creates a new file and values, but also saves them even when the player leaves.
There is actually a Roblox service that helps accomplish this very thing! The Roblox DataStore service is a service that allows you to save data at various called points throughout the game. At the bottom is a link to more about it. To save every value of the player’s leader stats (“Points” and “Xp”), you could create an empty dictionary and iterate over the values of your leader stats while adding them to the dictionary to be saved (This also makes it more convenient if you want to add more in future).
Example of this would be:
local playerData = {}
for each,stat in pairs(player.leaderstats:GetChildren()) do
playerData[stat.Name] = stat.Value
end
You could then update a datastore with this data when the player leaves and load it back when a player rejoins the game.
You should use the video I posted to understand better. It accomplishes exactly what you are asking. Don’t just watch it, follow along in your code with it so you can learn better. It’s a lot easier to understand something when you can troubleshoot and think over it.
local DSS = game:GetService("DatastoreService") -- Gets service
local pointsDS = DSS:GetDataStore("points") --Creates data store using the name in parameters
game.Players.PlayerAdded:Connect(function(player)
local points = Instance.new("IntValue", player) --Instancing a value into the player, you could do this in a folder if you want it organized
points.Value = pointsDS:GetAsync(plr.UserId) or 0--The value of the Instance will try to find the saved value in the DataStore if it doesn't then the value will be false
end)
game.Players.PlayerRemoving:Connect(function(player)
local points = player.Points --Getting the value from our player
local success, errorMsg = pcall(function() --If you don't know what pcalling is consider reading about it in Roblox DevHub
pointsDS:SetAsync(plr.UserId)
end)
if errormessage then
print("Error occured while saving data!")
end
end)