Hello, I’ve run across an issue with the saving of data with my Datastore. Every time I’ve exited the game in Roblox (In-Game) and in Studio, it hasn’t saved once. However it has saved on respawn. Can anyone help me fix this issue?
local statsholder = script.Data
game.Players.PlayerAdded:Connect(function(plr)
local key = "Player-ID:" .. plr.UserId
local save = dataholder:GetAsync(key)
local folder = statsholder:Clone()
folder.Parent = plr
if save then
for i,v in pairs(statsholder:GetChildren()) do
folder[v.Name].Value = save[1]
print(i,v.Name,v.Value)
end
else
local tosave = {}
for i,v in pairs(dataholder:GetChildren()) do
table.insert(tosave, v.Value)
print(i,v.Name,v.Value)
end
dataholder:SetAsync(key,tosave)
end
while wait(30) do
local tosave = {}
for i,v in pairs(dataholder:GetChildren()) do
table.insert(tosave, v.Value)
print(i,v.Name,v.Value)
end
dataholder:SetAsync(key,tosave)
end
end)
local RunService = game:GetService("RunService")
game.Players.PlayerRemoving:Connect(function(plr)
local key = "Player-ID:" .. plr.UserId
local tosave = {}
for i,v in pairs(dataholder:GetChildren()) do
table.insert(tosave, v.Value)
print(i,v.Name,v.Value)
end
dataholder:SetAsync(key,tosave)
end)
game:BindToClose(function()
if RunService:IsStudio() then
wait(3)
end
end)
I’ve been looking over this for awhile now and I’m not seeing anything that could cause this to be breaking. Could you possibly add a print() at the start and end of the PlayerRemoving function?
Yeah, I added a print(“player leaving”) to the start and a print(“data saved”) to the end. In studio it prints both perfectly fine, however the data will not save. It does the same for in game.
Try testing with two different players. Have one leave first, and the other about ten seconds later.
If only the first player’s data is being saved, it’s probably a case of the server shutting down before the data is saved.
My best guess is to wrap your autosave function like this
local function autosave(Key)
local savecoroutine = coroutine.wrap(function(Key)
while wait(30) do
local tosave = {}
for i,v in pairs(dataholder:GetChildren()) do
table.insert(tosave, v.Value)
print(i,v.Name,v.Value)
end
dataholder:SetAsync(Key,tosave)
end
end)
end
end
and for firing it do autosave(key)
I suggest using Datastore2. It is a lot more secure and a lot easier to save and load data with.
For answering your question, I suggest starting new threads with the coroutine feature.
For example, at the while wait(30)
part you can do
coroutine.wrap(function()
while wait(30) do
local tosave = {}
for i,v in pairs(dataholder:GetChildren()) do
table.insert(tosave, v.Value)
print(i,v.Name,v.Value)
end
dataholder:SetAsync(key,tosave)
end
end)()
2 Likes