Why doesn't it set the Begginers Cash to 100

Any Idea why it isn’t set to 100?

local ds = game:GetService("DataStoreService")
local datastore = ds:GetDataStore("JunkyardCash")
game.Players.PlayerAdded:Connect(function(player)
	local Cash = Instance.new("NumberValue")
	Cash.Name = "Cash"
	Cash.Value = 100
	Cash.Parent = player
	
	local data
	local success, errormessage = pcall(function()
		data = datastore:GetAsync(player.UserId.."-cash")
	end)
	
	if success then
		Cash.Value = data
	else
		print("There was an error while getting your cash")
		warn(errormessage)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local success, errormessage = pcall(function()
		datastore:SetAsync(player.UserId.."-cash", player.Cash.Value)
	end)
	if success then
		print("Your cash was saved!")
	else
		print("Couldn't save cash")
		warn(errormessage)
	end
end)

You don’t check to see if the player’s data is nil before assigning the new value

1 Like
if success and data then
		Cash.Value = data

if you set a NumberValue to nil it will automatically become a 0 and since you’re just checking if retriving the data was a success and you’re not checking if the data is nil it is setting it to be 0 and since I take it you have tested alot, it might have saved as 0 in the datastore

1 Like

That sadly didn’t work the same issue is appering! :frowning:

You are setting the Value of Cash to nil when they haven’t played yet. This will default the Value to 0 if data is nil. setting the Value to data or 100 will set it to data’s value if it is not nil otherwise, it will set it to 100.

game.Players.PlayerAdded:Connect(function(player)
	local data
	local success, errormessage = pcall(function()
		data = datastore:GetAsync(player.UserId.."-cash")
	end)
	
	if success then
        local Cash = Instance.new("NumberValue")
	    Cash.Name = "Cash"
	    Cash.Value = data or 100
	    Cash.Parent = player
	else
		print("There was an error while getting your cash")
		warn(errormessage)
	end
end)

Edit: This next response was replying to someone else’s (incorrect) assumption around pcall() and :GetAsync() but feel as though it’s valuable information (regardless of it you are aware of this already) so I will paste it below.

I think there is confusing here around the pcall(). The pcall() around the :GetAsync() is not checking if the value exists within the datastore. This pcall() is checking if there was an error while attempting to receive the data from roblox. This error is almost always due to roblox servers being down. Assuming Roblox’s servers are fine, regardless of if it is the player’s first time playing or not, the if success then line will evaluate as true and create the Cash instance.

1 Like

Forget I’m dumb :zipper_mouth_face: sorry, 30 symbols