0

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

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 gold = Instance.new("IntValue") --Sets up value for leaderstats

gold.Name = "Coins"

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

end)

if not success then

warn('Could not save data!')

end

end

game.Players.PlayerRemoving:Connect(onPlayerExit)


0

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