Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

My DataStore isn't saving leaderstats?

Hi. I'm trying to make a data store that saves the amount of cash someone has. But the problem is that it isn't saving. Here is the code.

local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")


function playerJoin(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	local Cash = Instance.new("IntValue")
	Cash.Name = "Cash"
	Cash.Value = 0
	Cash.Parent = leaderstats
	
	local playerUserId = "Player_"..player.UserId
	--Load Data
	local data
	local success, errormessage = pcall(function()
		local data = myDataStore:GetAsync(playerUserId)
	end)
	
	if success then
		Cash.Value = data
		-- Set our data to the current Money
		
	end
	
	
end

game.Players.PlayerRemoving:Connect(function(player)
	local playerUserId = "Player_"..player.UserId
	local data = player.leaderstats.Cash.Value
	local success, errormessage = pcall(function()
	myDataStore:SetAsync(playerUserId, data)	
	end)
	if success then
		print("Data Succesfully Saved!")
	else
		print("There was an error when saving data!")
		warn(errormessage)
	end
end)

game.Players.PlayerAdded:Connect(playerJoin)

1 comment

0

Put print statements to debug it.

1 answer

✓ Accepted answer

When using Players.PlayerRemoving event, it doesn't save the last player in the server, the reason why is because the server instantly shuts down when the last player leaves. A way to solve that is use game:BindToClose(). game:BindToClose() is a function that allows to run any code for 30 seconds before the server fully shuts down. Here's how you can solve it:

game:BindToClose(function()
	for _, v in pairs(game.Players:GetPlayers()) do
		local userId = v.UserId
		local data = v.leaderstats.Cash.Value
		local success, errorMessage = pcall(function()
			myDataStore:SetAsync(userId,data)
		end)
		if success then
			print("Data saved and server closed")
		else
			warn("Error while saving data: "..errorMessage)
		end
	end
end)

Source: DataModel:BindToClose()

1 comment

0

I get the "data saved and server closed" but the data doesn't save?

This discussion is preserved as it was. New answers, comments, and votes are closed.