Hey guys, I’ve been working on a game and needed a datastore. I found a tutorial on YouTube and followed along with it and the datastore works really well. The only issue is that I noticed that when my power went out (while playing my game), when I rejoined, my data was reset. Does anyone know how to prevent data loss like this in the future?
ServerScript:
local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetDataStore("Player")
local loaded = {}
game.Players.PlayerAdded:Connect(function(player)
local success, value = pcall(dataStore.GetAsync, dataStore, player.UserId)
if success == false then player:Kick("DataStore failed to load") return end
local data = value or {}
print("Loaded:", data)
for i, folder in game.ServerStorage.PlayerData:GetChildren() do
local subData = data[folder.Name] or {}
local clone = folder:Clone()
for i, child in clone:GetChildren() do
child.Value = subData[child.Name] or child.Value
end
clone.Parent = player
end
loaded[player] = true
end)
game.Players.PlayerRemoving:Connect(function(player)
if loaded[player] == nil then return end
local data = {}
for i, folder in game.ServerStorage.PlayerData:GetChildren() do
local subData = {}
for i, child in player[folder.Name]:GetChildren() do
subData[child.Name] = child.Value
end
data[folder.Name] = subData
folder:Destroy()
end
local success, value = pcall(dataStore.SetAsync, dataStore, player.UserId, data)
print("Saved:", data)
loaded[player] = nil
end)
game:BindToClose(function()
while next(loaded) ~= nil do
task.wait()
end
end)
Note: I can script a lot of things, but DataStores aren’t one of them. I have no idea how to make changes to the DataStore script without breaking it…
Any help is much appreciated!