Help with DataStore not saving/working (PlayerRemoving/game:BindToClose)

I added BindToClose to your script. See if this works:

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

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local Name = Instance.new("StringValue")
	Name.Name = "NickName"
	Name.Parent = leaderstats

	local PlayerUserid = "Player_"..player.UserId

	local Data

	local success, errormessage = pcall(function()
		Data = DataStore1:GetAsync(PlayerUserid)
	end)
	if success then
		if Data ~= nil then
			Name.Value = Data
		else
			Name.Value = player.Name
		end
	else
		print(errormessage)
	end
end)

local GameClosing = false

game.Players.PlayerRemoving:Connect(function(player)
	if GameClosing ~= true then
		local PlayerUserid = "Player_"..player.UserId
		local Data = player.leaderstats.NickName.Value

		local success, errormessage = pcall(function()
			DataStore1:SetAsync(PlayerUserid, Data)
		end)
		if success then
			print("Data was saved")
		else 
			print("There was an error")
			warn(errormessage)
		end
	else return end
end)

game:BindToClose(function()
	GameClosing = true
	for i, Player in pairs(game.Players:GetPlayers()) do
		local Data = Player.leaderstats.NickName.Value
		local PlayerUserid = "Player_"..Player.UserId
		local success, errormessage = pcall(function()
			DataStore1:SetAsync(PlayerUserid)
		end)
		if not success then
			print(errormessage)
		end
	end
end)

Let me know if there are any errors.

1 Like

I’ve recently made a new Post, I am rewriting code so this might help.