Data stores can't handle my request or?

Hello!
I’m making my data stores and when I getting values it works
but when I saving datas it probably do not handle it bc still it saying new player unless I have been joined
My script:

local ServerData = game:GetService("DataStoreService"):GetDataStore("Global_Leaderstats")
game.Players.PlayerAdded:Connect(function(plr)
	print("Player joined")

	local CoinsClientData = ServerData:GetAsync(plr.UserId.."-Coins")
	local PetsClientData = ServerData:GetAsync(plr.UserId.."-Pets")
	local EffectsClientData = ServerData:GetAsync(plr.UserId.."-Effects")
	local Leaderstats = Instance.new("Folder",plr)
	Leaderstats.Name = "leaderstats"
	
	local Coins = Instance.new("IntValue",Leaderstats)
	Coins.Name = "Coins"
	plr2 = plr
	if PetsClientData ~= nil and CoinsClientData ~= nil and EffectsClientData ~= nil then
		Coins.Value = CoinsClientData
		PetsClientData.Parent = plr
		EffectsClientData.Parent = plr
		print("Pets and Coins laoded in")
	else
		Coins.Value = 0
		local PetsFolder = Instance.new("Folder",plr)
		PetsFolder.Name = "Pets"
		local EffectFolder = Instance.new("Folder",plr)
		EffectFolder.Name = "Effects"
		print("No data to load! Loading into game a new player!")
		end
end)
game.Players.PlayerRemoving:Connect(function(plr)

		ServerData:SetAsync(plr.UserId.."-Coins",plr.leaderstats.Coins.Value)
		ServerData:SetAsync(plr.UserId.."-Pets",plr.Pets)
		ServerData:SetAsync(plr.UserId.."-Effects",plr.Effects)
end)
game:BindToClose(function()
		ServerData:SetAsync(plr2.UserId.."-Coins",plr2.leaderstats.Coins.Value)
		ServerData:SetAsync(plr2.UserId.."-Pets",plr2.Pets)
		ServerData:SetAsync(plr2.UserId.."-Effects",plr2.Effects)
end)

Thank for any help!

On your BindToClose() function you are calling the variable plr2, but I don’t see where you’ve defined that variable. Maybe that could be erroring when the game closes therefore not saving data?

I know that PlayerRemoving can sometimes not save data after the last person left, so maybe you’re BindToClose() is erroring and PlayerRemoving function isn’t saving it either.

This is a less likely problem, but is it possible that you’re not changing the data through a script? that problem tampered me for a while since I was changing it through explorer in Roblox Studio and It didn’t work.

You can create a pairs loop inside the BindToClose() function and loop through all the players in the server and save their data.

I suggest you to put the GetAsync() and SetAsync() in a pcall function, because datastore requests sometimes fail.
And as the others above me said, you don’t have a variable called plr2.
In the following pages you can see how to put your Get and Set in pcalls:
How to use Pcalls and when

Data stores

1 Like