DataStore won't save Number Value

So I am new to using Data Stores, and this is currently my first time. I am trying to save a number Value but for some reason It just wont. I’ve tried multiple forum pages and tutorials but none of them seem to work properly.

Heres the code

local DataService = game:GetService('DataStoreService')
local plrData = DataService:GetDataStore('CoolDownTimeData')

local function onPlayerJoin(player)
	local price = player.PlayerGui:WaitForChild("ShopGui").Mainframe.ShortenCooldown.price
	print("Player Added")
	
	local userId = player.UserId
	print(player.Name.."'s ID is "..player.UserId)
	
	local data = plrData:GetAsync(userId)
	
	if data then
		price.Value = data
	else
		price.Value = 10
	end
end

local function onPlayerLeave(player)
	local success, err = pcall(function()
		local userId = player.UserId
		plrData:SetAsync(userId, player.PlayerGui.ShopGui.Mainframe.ShortenCooldown.price.Value)
	end)
	if not success then
		warn('Couldnt save the data!')
	end
end

game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerLeave)

This is the error message I get.
image

Anything will help!

1 Like

What is the error you get? Unsuccessful pcalls return an error message, which in your case is err.


Bruh! so while leaving, the PlayerGui gets destroyed before the data can be saved.

Then you may want to look to keeping that value somewhere else.

You shouldn’t be calling the actual value, instead, do the following:

local function onPlayerJoin(player)
	local price = player.PlayerGui:WaitForChild("ShopGui").Mainframe.ShortenCooldown.price
	print("Player Added")
	
	local userId = player.UserId
	print(player.Name.."'s ID is "..player.UserId)
	
	local data = plrData:GetAsync(userId)
	
	if data then
		price.Value = data.Price
	else
		price.Value = 10
	end
end

local function onPlayerLeave(player)
	local success, err = pcall(function()
		local userId = player.UserId
        local data = {}
        data.Price = player.PlayerGui.ShopGui.Mainframe.ShortenCooldown.price.Value
		plrData:SetAsync(userId, data)
	end)
	if not success then
		warn('Couldnt save the data!')
	end
end


and now there is another problem.

I assume data.Price does not exist