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

Why is my data saving script not working?

Here is my script:

local datastore = game:GetService("DataStoreService")
local datas = datastore:GetDataStore("MyDataStore")

game.Players.PlayerAdded:Connect(function(plr)
-- leaderboard
	local stats = Instance.new("Folder")
	stats.Name = "leaderstats"
	stats.Parent = plr
	
	local kills = Instance.new("IntValue")
	kills.Name = "Kills"
	kills.Parent = stats
	
	local deaths = Instance.new("IntValue")
	deaths.Name = "Deaths"
	deaths.Parent = stats
	
	local coin = Instance.new("IntValue")
	coin.Name = "Coins"
	coin.Parent = stats
	coin.Value = 10
	
--Data Value
	local plrID = "user_"..plr.UserId
	local Data
	local success, err = pcall(function()
		Data = datas:GetAsync(plrID)
	end)
	-- Value
	if success and Data then
		print("Data Loading")
		kills.Value = Data[1]
		deaths.Value = Data[2]
		coin.Value = Data[3]
	elseif err then
		print("Error with Loading Data")
		warn(err)
	end
	
	-- On death event
	plr.CharacterAdded:Connect(function(char)
		local humanoid = char:FindFirstChild("Humanoid")
		humanoid.Died:Connect(function()
			deaths.Value = deaths.Value + 1
		end)
	end)
end)

--Saving data
game.Players.PlayerRemoving:Connect(function(plr)
	local success, err = pcall(function()
		local plrID = "user_"..plr.UserId
		datas:SetAsync((plrID), {
		plr.leaderstats.Kills.Value,
		plr.leaderstats.Deaths.Value,
		plr.leaderstats.Coins.Value
		})
	end)
	if success then
		print("Data Saved")
	else
		print("There is an error")
		warn(err)
	end
end)

The values of the data isn't saved. How can I fix this?

1 answer

✓ Accepted answer

When there are 0 players left in the game, the server immediately shuts down. However, there is a way to delay this. It is called game:BindToClose(function). Basically, you put a function as an argument, then whenever the server shuts down the function you sent will run.

-- Function Code

game:BindToClose(function()
	-- Kick everyone in the server
	for _, player in pairs(game.Players:GetPlayers()) do
		player:Kick()
	end
	wait(5) -- This is enough time for a player's data to save
end)

--While the wait() function is running, the game.Players.PlayerRemoving event is also running.

So basically, just add this to your script. If it still does not work, turn on the api services. I hope this helps.

1 comment

0

Thank you so much!, I have some questions tho, the part '_,player', where did you get the player from and what does the _ means???I added that to my script and it worked well! Thank you!

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