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.

4 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.

4 Likes

Hey I know it’s been a while since this post was created but I actually need help with this because I have a similar thing that I would like to add in one of my future games

Could you help me out?

Sure! It’s been nearly two years since making this post and I now have made my own saving module so feel free to tell me what’s the matter with your game, It’ll be a pleasure to provide my knowledge of DataStoreService

its basically the same thing as the original post, theres a button in my game and i need a counter that goes up for everybody every time someone clicks, i tried rogchamp’s solution but it doesnt work quite well