Datastore code doesn't work [Closed]

I want to save & load players “Superbux” that the player can exchange for items. The starting amount is 5000.

My codes:
ServerScript (Superbux)

local stat = "Superbux"
local startamount = 5000

local DataStore = game:GetService("DataStoreService")
local ds = DataStore:GetDataStore("PlayerDataGame")
local pl = game:GetService("Players")

pl.PlayerAdded:Connect(function(plr)
	local folder = Instance.new("Folder")
	folder.Name = "leaderstats"
	folder.Parent = plr
	local intvalue = Instance.new("StringValue")
	intvalue.Name = stat
	intvalue.Value = startamount
	intvalue.Parent = folder
	local success, data = pcall(function()
		return ds:GetAsync(plr.UserId)
	end)
	if success then
		local data2 = string.gsub(data, "Instance", "")
		intvalue.Value = data2
	end
end)

LocalScript (Pay)

local lp = game:GetService("Players").LocalPlayer

script.Parent.MouseButton1Click:Connect(function()
	if lp:FindFirstChild("leaderstats") and lp.leaderstats:FindFirstChild("Superbux") then
		local total = 0
		for _, item in pairs(lp.Backpack:GetChildren()) do
			if item:FindFirstChild("Price") and typeof(item.Price.Value) == "number" then
				local price = item.Price.Value
				if price > 0 then
					total = total + price
					item.Price.Value = 0
				end
			end
		end
		lp.leaderstats.Superbux.Value = lp.leaderstats.Superbux.Value - total
		game:GetService("ReplicatedStorage").SavePlayerData:FireServer()
	end
end)

ServerScript (SavePlayerDataHandler)

game:GetService("ReplicatedStorage").SavePlayerData.OnServerEvent:Connect(function(plr)
	game:GetService("DataStoreService"):GetDataStore("PlayerDataGame"):SetAsync(plr.UserId, plr.leaderstats.Superbux.Value)
	print(game:GetService("DataStoreService"):GetDataStore("PlayerDataGame"):GetAsync(plr.UserId))
end) 
1 Like

maybe try out profile service, that can even prevent dupe

1 Like

Here you’re modifying the SuperBux leaderstat variable on the client side and not the server. Client side value modifications are not replicated to the server and the server will not recognize the value’s change.

Something else to note is when it comes to player data like a player’s currency, unlocks, inventory, etc, those should never allow the client to change it as exploiters and client side exploits could be used and players could easily give themselves virtually infinite currency or the best items in the game.

Instead you should have the client tell the server that they want to buy something and have the server calculate everything else.

Another thing, when getting a key from a DataStore and there is no value for that key it will not throw and error and instead return nil. Make sure to check the type of the data before using it.

Also, I recommend renaming DataStore to DataStoreService and ds to either DataStore or PlayerDataDataStore if you feel you will be adding more DataStores.

3 Likes

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