I want to make a datastore for my high score to save so players can see it when they log in later. The only problem is when I leave and rejoin it doesn’t save. I’ve tried it in studio and on Roblox. I don’t know what’s wrong.
Serverscript Service Highscore Script …
local function loadHighScore(player)
local success, result = pcall(function()
return game:GetService(“DataStoreService”):GetDataStore(“HighScores”):GetAsync(tostring(player.UserId))
end)
if success and result then
return result
else
return 0
end
end
local function saveHighScore(player, score)
local success, _ = pcall(function()
game:GetService(“DataStoreService”):GetDataStore(“HighScores”):SetAsync(tostring(player.UserId), score)
end)
end
game.Players.PlayerAdded:Connect(function(player)
local highScore = loadHighScore(player)
local highScoreValue = Instance.new(“IntValue”)
highScoreValue.Name = “HighScore”
highScoreValue.Value = highScore
highScoreValue.Parent = player
local playerRemovingConnection
playerRemovingConnection = game.Players.PlayerRemoving:Connect(function()
saveHighScore(player, highScoreValue.Value)
playerRemovingConnection:Disconnect()
end)
This shouldn’t be set up like this. Just make one primary listener like Players.PlayerAdded because with the way it’s written inside the signal, this would fire and save the players’s data automatically if anyone leaves the game (then it won’t save again). Players.PlayerRemoving sends the player who left, so wrapping it isn’t neccessary.
As for your main issue, are you updating the player’s score from the client?
I don’t mean if the HighScore object is created on the client/server; i’m asking if the value of the high score is being changed from the client or the server
(You can also add this to the bottom of the script)
-- To decrease the chances of data loss, this keeps the server open for a few more seconds
-- to be absolutely sure that the player's data is saved
game:BindToClose(function()
for _, plr in game.Players:GetPlayers() do
saveHighScore(plr, plr.HighScore.Value)
end
end)