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

Datastorage does not save data when leaving, how to fix?

Asked by 3 years ago

I tried making my own script but after several hours and many fails i searched a tutorial. I followed all the steps and changed the stats to my own. I dont know if you should add any stringvalues or anything, as for now i just have this script:


local DataStoreService = game:GetService("DataStoreService") local playerData = DataStoreService:GetDataStore("PlayerData") local function onPlayerJoin(player) -- Runs when players join local leaderstats = Instance.new("Folder") --Sets up leaderstats folder leaderstats.Name = "leaderstats" leaderstats.Parent = player local gold = Instance.new("IntValue") --Sets up value for leaderstats gold.Name = "Coins" gold.Parent = leaderstats local playerUserId = "Player_" .. player.UserId --Gets player ID local data = playerData:GetAsync(playerUserId) --Checks if player has stored data if data then -- Data exists for this player gold.Value = data else -- Data store is working, but no current data for this player gold.Value = 0 end end local function onPlayerExit(player) --Runs when players exit local success, err = pcall(function() local playerUserId = "Player_" .. player.UserId playerData:SetAsync(playerUserId, player.leaderstats.Gold.Value) --Saves player data end) if not success then warn('Could not save data!') end end game.Players.PlayerAdded:Connect(onPlayerJoin) game.Players.PlayerRemoving:Connect(onPlayerExit)

1 answer

Log in to vote
0
Answered by 3 years ago

If you are testing and you are the only one in you server, the server shuts down when you leave and the code wont run. To prevent this, add another block of code that includes this

game:BindToClose(function()
    for _, player in pairs(game.Players:GetPlayers()) do

        local Id = "player_"..player.UserId
        local Data = player.leaderstats.Cash.Value

            local success, errormessage = pcall(function()
            DataStore1:SetAsync(Id, Data)
                print("DataSaved")
            end)

        if success then
                print("DataSaved")
        elseif errormessage then
            print("There was a error")
warn(errormessage)
        end
    end
end)

Put this under your other code

Ad

Answer this question