SetAsync not setting my data

I’m learning datastore service, and this was working for me yesterday but isn’t working anymore.

game.Players.PlayerAdded:Connect(function(plr)
	local data = game:GetService("DataStoreService"):GetDataStore("a"):GetAsync(plr.UserId)
	print(data)
end)

game.Players.PlayerRemoving:Connect(function(plr)
	game:GetService("DataStoreService"):GetDataStore("a"):SetAsync(plr.UserId, 1)
end)

I have API services enabled, but it always prints nil. Can anyone help?

1 Like

Hey there!

This looks like a bug from Roblox that is easily fixable. You can do the following things:
Print out ‘Start!’ at the end of the PlayerAdded function. Do the same with the PlayerRemoving function but print out ‘End!’ at the last line. Now you should notice that ‘Start!’ is being printed but ‘End!’ isn’t.

You can prevent this by writing the following code at the beginning of the script:

local RunService = game:GetService('RunService')
local CanCloseServer = false
game:BindToClose(function()
	while RunService:IsRunning() and not CanCloseServer do
		task.wait()
	end
end)

Now add CanCloseServer = true at the very last line of your PlayerRemoving function. This results in the game being prevented from stopping until PlayerRemoving is fully executed.

Here’s your fixed code:

local RunService = game:GetService('RunService')
local CanCloseServer = false
game:BindToClose(function()
	while RunService:IsRunning() and not CanCloseServer do
		task.wait()
	end
end)
game.Players.PlayerAdded:Connect(function(plr)
	local data = game:GetService("DataStoreService"):GetDataStore("a"):GetAsync(plr.UserId)
	print(data)
end)

game.Players.PlayerRemoving:Connect(function(plr)
	game:GetService("DataStoreService"):GetDataStore("a"):SetAsync(plr.UserId, 1)
    CanCloseServer = true
end)

Also make sure that the script is a Script in ServerScriptService.
If you have any further questions don’t hesitate to ask me!

1 Like

Thanks so much. I really appreciate your detail. I understand how this works now!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.