I am trying to use a datastore but it is always storing the wrong value (0) instead of what I earned (125) (Tested in Studio and Roblox, you can see the game here) "Allow studio to access API services" is enabled My code:

local DataStoreService = game:GetService("DataStoreService")
local dataStore = DataStoreService:GetDataStore("GAME")
local p

game.Players.PlayerAdded:Connect(function(player)
	p = player
	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Parent = player
	
	local userid = "Player_"..player.UserId
	local data1
	local success, err = pcall(function()
		data1 = dataStore:GetAsync(userid.."-coins")
	end)

	if success then
		print("Load success!")
		if coins then
			coins.Value = data1
			game.StarterGui.ScreenGui.TextLabel.Text = coins.Value
		end
	else
		warn("Failed to load data: "..err)
	end
	
end)

function remove(player)
	local coins = player.Coins
	local val = coins.Value
	local userid = "Player_"..player.UserId
	local success, err = pcall(function()
		dataStore:SetAsync(userid.."-coins",val)
	end)
	if success then
		print("Save success. Data: "..val)
	else
		warn("Save failed. Error: "..err)
	end
end

game:BindToClose(function()
	remove(p)
	wait(2)
end)

4 comments

0

The correct way to listen for players leaving the game is game.Players.PlayerRemoving, just like how you would use game.Players.PlayerAdded to listen for players joining the game. Make this change and see if the problem persists.

0

No, that did not fix it.

0

Hmm... it looks like on Line 21 you update a TextLabel in StarterGui. Nobody will actually see this change however, since everything in StarterGui gets replicated to the PlayerGui once per spawn, and that is assuming that your GUI object resets on spawn. To replicate the changing of the value, you will need to make the update via player.PlayerGui.

0

The GUI is just for testing purposes.