My high score data doesn't save! (I have the API services on)

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)

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?

1 Like

So do I do …
game.Players.PlayerRemoving:Connect(function()
saveHighScore(player, highScoreValue.Value)
end)

1 Like

The script is set in in the ServerScript Service

1 Like
game.Players.PlayerRemoving:Connect(function(player)
    saveHighScore(player, player.HighScore.Value)
end)
1 Like

Ok let me see it if works
Thanks for helping me

1 Like

It still doesn’t work



1 Like

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)
1 Like

You forgot about the BindToClose function.

1 Like

Oh yeah I’m updating from the client (Late Reply)

1 Like

I know what to do now thanks! I am going to make a remote vent to update the high score on the server side

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.