DataSave script for time isn’t working and I don’t know why. No errors in the output. Here’s the script:
local myDataStore = DataStoreService:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Time = Instance.new("IntValue")
Time.Name = "Time"
Time.Parent = leaderstats
local playerUserId = "Player"..player.UserId
local data
local success, errormessage = pcall(function() print("kill me")
data = myDataStore:GetAsync(playerUserId)
end)
if success then
Time.Value = data
end
while wait(1) do
player.leaderstats.Time.Value = player.leaderstats.Time.Value + 1
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = "Player"..player.UserId
local data = player.leaderstats.Time.Value
myDataStore:SetAsync(playerUserId, data)
end)
Is it only not working in studio , or in Roblox as well, what I’ve noticed once while recording a tutorial video, if once you leave the game you do not see a Disconnected message, your data will not save!
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Time = Instance.new("IntValue")
Time.Name = "Time"
Time.Parent = leaderstats
local data
local succ, err = pcall(function()
data = myDataStore:GetAsync("Player"..player.UserId)
end)
if succ then
if data then
Time.Value = data
end
else
warn(err)
end
task.spawn(function()
while task.wait(1) do
player.leaderstats.Time.Value += 1
end
end)
end)
Players.PlayerRemoving:Connect(function(player)
local data
local succ, err = pcall(function()
data = myDataStore:SetAsync("Player"..player.UserId, player.leaderstats.Time.Value)
end)
if succ then
return
else
warn(err)
end
end)
game:BindToClose(function()
for _, player in ipairs(Players:GetPlayers()) do
local data
local succ, err = pcall(function()
data = myDataStore:SetAsync("Player"..player.UserId, player.leaderstats.Time.Value)
end)
if succ then
return
else
warn(err)
end
end
end)
You may also want to add a function which performs auto-saving every minute.
Ah okay. I always thought this because in studio if I save data too frequently it errors. But I do have it wrapped in a pcall so it doesn’t break the game. Does this only happen in studio or does it happen in the real game as well?
pcall() calls are necessary when making any API request, since when API requests fail, errors are raised/thrown, which results in the premature termination of scripts.