DataStore doesn't save if the player leaves the game

local DataStoreService = game:GetService("DataStoreService")
local DienstgradStore = DataStoreService:GetDataStore("Dienstgrade")

 game.Players.PlayerRemoving:Connect(function(plr)
    	local success, err = pcall(function()
    		DienstgradStore:SetAsync(plr.UserId, game.Players:FindFirstChild(plr.Name):WaitForChild("leaderstats"):FindFirstChild("Dienstgrad").Value)
    	end)
    	if success then
    		print("success!")
    	elseif err then
    		print("Error!")
    	end
    end)

It gives me no error in the output and no success and if I get the Data it’s nill, so it don’t save it. Thanks for help.

1 Like

I think the issue is the fact that your aren’t including game:BindToClose().
You see, when there is only one person left in a server, and that person leaves, the server automatically closes. However, due to this, there isn’t enough time to save the data before the server closes, which is why you use game:BindToClose()

This built-in function yields the server closure for 30 seconds (This is off the top of my head), allowing enough time to successfully set data to the datastore, so I recommend you use it, unless you want a lot of data lost.

API Refererence

Ill try it. Thanks for the help.

1 Like

That looks right, but on another note, what’s going on with the whole FindFirstChild thing? The PlayerRemoving event already passes the player instance as an argument, so you don’t need to find another reference for it. Another way to write out your pcall:

local leaderstats = plr:FindFirstChild("leaderstats")
if not leaderstats then return end

local playerDienstgrad = leaderstats:FindFirstChild("Dienstgrad")
if not playerDienstgrad then return end

local success, err = pcall(function ()
    return DienstgradStore:SetAsync(plr.UserId, playerDienstgrad.Value)
end)
1 Like