Help with Item Count Script

I have a script for counting items, which involves a straightforward leaderstats and datastore script. It saves the items every 20 seconds. Everything functions well, except when there is more than one server. If one server saves five additional items, the others will not receive that update and will save the previous value instead. How can I resolve this issue?

Use UpdateAsync to review the current value and modify the value.
Basically does same as GetAsync and SaveAsync combined into 1 call.

You will need a means to sanity check what data you want to keep and what data can be overwritten. I don’t fully know what you are attempting so I can’t give you a tailored approach.

Some other approaches or similar would be:

  • Polling DataStore data frequently to update each server before any server makes overwrites to ensure the data that is saved is always accurate
  • Make use of MessengingService to send messages to all servers to keep all servers in-sync

Some combination of UpdateAsync and MessagingService would be your best bet I think.

1 Like

So, UpdateAsync() isn’t working, could it be because it doesn’t yield scripts? (and it doesn’t print out my success print)

Example of how UpdateAsync() can be used

local DataStoreService = game:GetService("DataStoreService")
local highScoreDataStore = DataStoreService:GetDataStore("HighScoreStore")

-- Function to update the player's high score
local function updateHighScore(player, newScore)
    -- Use UpdateAsync to safely update the player's high score
    local success, err = pcall(function()
        highScoreDataStore:UpdateAsync(player.UserId, function(currentScore)
            -- Check if the current score exists or if the new score is higher
            if currentScore == nil or newScore > currentScore then
                return newScore -- Update to the new high score
            else
                return currentScore -- Keep the existing high score if it's higher
            end
        end)
    end)
    
    if success then
        print("High score updated successfully for player:", player.Name)
    else
        warn("Failed to update high score:", err)
    end
end

game.Players.PlayerAdded:Connect(function(player)
    local newScore = math.random(50, 200

Documentation: GlobalDataStore | Documentation - Roblox Creator Hub

So, it takes a function as a parameter? Anyway I got it to work, it should save across servers now.

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