Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I change and save the leaderstats after a shop is used to buy an item?

Asked by 3 years ago

I can't seem to get my shop GUI to change the Cash value in my player.leaderstats. I either get the error 'Cash is not a valid member of IntValue' or if I mess around with the code a little bit nothing at all happens or my leaderstats disappears in game.

Question: How do I get the shop to access the leaderstats so the buttons within the frame change and SAVE the player's leaderstats when they buy an item?

local Players = game:GetService("Players")
local goldDataStore = game:GetService("DataStoreService"):GetDataStore("Cash") 

local STARTING_CASH = 100

local function onPlayerAdded(player)
    local playerKey = "Player_" .. player.UserId

    local leaderstats = Instance.new("IntValue")
    leaderstats.Name = "leaderstats"

    local Cash = Instance.new("IntValue", leaderstats)
    Cash.Name = "Cash"

    local myCash
    local success, err = pcall(function()
        myCash = goldDataStore:GetAsync(playerKey) or STARTING_CASH
    end)
    if success then
        Cash.Value = myCash
    else
        -- Failed to retrieve data
    end

    leaderstats.Parent = player
end

for _, player in pairs(Players:GetPlayers()) do
    onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

Above is my LoadData script, which seems to work just fine but I could be wrong.

local pointsDataStore = game:GetService("DataStoreService"):GetDataStore("Cash")

game.Players.PlayerAdded:Connect(function(player)
    local playerKey = "Player_" .. player.UserId
    -- Give 50 points to players each time they visit
    local success, err = pcall(function()
        pointsDataStore:UpdateAsync(playerKey, function(oldValue)
            local newValue = oldValue or 0
            newValue = newValue + 50
            return newValue
        end)
    end)
end)

Above is my SaveData script. When I change my Cash value in player properties and rejoin the game my Cash value does not save to what I changed it to. Somehow it saves that extra +50 every time and it keeps adding up which proves something in the save is working. I do not want newValue being shown in the leaderstats, I want the actual leaderstats to be there and updated every time something in the shop is bought.

Sorry if this is a lot. I'm very close to figuring this out which will help me finally publish my first game. Any help is appreciated!

Answer this question