Saving a global value

So, Imagine that there is a button, when a player clicks It, 1 point is added to a global counter, and that counter is the same for every player in-game, and even when all the players leave the game, when they come back, the counter will remain the same It was last time, basically a public/global datastore?

Just save to a key that doesn’t involve the player’s UserId in any way. You can use UpdateAsync so that it can get whatever other servers have saved.

3 Likes

@rogchamp is right, an example of this would be,

local DataStore = game:GetService("DataStoreService"):GetDataStore("GlobalCounter")
local Key = "CounterKey"

button.MouseButton1Click:Connect(function()
    local Data
    local success, err = pcall(function()
        Data = DataStore:GetAsync(Key)
    end)
    if not success then warn(err) else -- there was an error
        if Data == nil then Data = 0 end -- If data is "nil" then we set it to zero as the default value
        Data = Data + 1
        local success2, err2 = pcall(function()
            DataStore:SetAsync(Data, Key)
        end)
        if not success2 then warn(err2) end
    end
end) 

This isn’t the best way of getting/saving the data since in my example I’m getting/saving it everytime the button is clicked. This is just a rough example of how you can do this.

2 Likes