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)