i am trying to make a game and the leaderboard data should save but isn't. here is the code in serverscriptservice:
local DataStoreService = game:GetService("DataStoreService")
local statsDS = DataStoreService:GetDataStore("statsDS")
local SAVE_INTERVAL = 60 -- Save data every 60 seconds (1 minute)
-- Helper function to save player data
local function savePlayerData(player)
local leaderstats = player:FindFirstChild("leaderstats")
if leaderstats then
local Clicks = leaderstats:FindFirstChild("Clicks")
local Time = leaderstats:FindFirstChild("Time")
if Clicks and Time then
local data = {Clicks.Value, Time.Value}
local playerUserId = "Player" .. player.UserId
local success, errorMessage = pcall(function()
statsDS:SetAsync(playerUserId, data)
end)
if success then
print("Saved data for " .. player.Name)
else
warn("Error saving data for " .. player.Name .. ": " .. errorMessage)
end
end
end
end
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Clicks = Instance.new("IntValue")
Clicks.Name = "Clicks"
Clicks.Parent = leaderstats
local Time = Instance.new("IntValue")
Time.Name = "Time"
Time.Parent = leaderstats
local playerUserId = "Player" .. player.UserId
local data = statsDS:GetAsync(playerUserId)
if data then
Clicks.Value = data[1]
Time.Value = data[2]
end
player:WaitForChild("leaderstats")
player:WaitForChild("leaderstats"):WaitForChild("Clicks")
local lastSaveTime = tick()
local saveTimer
saveTimer = game:GetService("RunService").Heartbeat:Connect(function()
if tick() - lastSaveTime >= SAVE_INTERVAL then
lastSaveTime = tick()
savePlayerData(player)
end
if not player:IsDescendantOf(game) then
-- Player left the game
saveTimer:Disconnect()
savePlayerData(player)
end
end)
end)
game.Players.PlayerRemoving:Connect(function(player)
savePlayerData(player)
end)
i was expecting the data to save when i leave and rejoin, but it is reset to 0
i tried messing around with the code in every which way but nothing worked and most just made it worse.
this is a game where there is a button and you click it and it adds to the value clicks and time just shows how much time you spent in the game. the following code should save it so it works between servers but it is never working. always resets. i dont know what else to add to fix it.
I have found out that everything was client side and none of the data was being on the server. now it works fine.