Recently I’ve been having some issues with my datastores saving and loading data and I would like for you guys to critique it and tell me what I could do to improve this/ prevent further data issues.
Sorry for the 100 line code in advance.
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")
local DataStore = DataStoreService:GetDataStore("xxxx")
--// Settings \\--
local Data = {
Music_Volume = .25;
SFX_Volume = 1;
Crouch = 306;
Jump = 32;
Reload = 114;
Zoom = 113;
Nade = 103;
};
local SaveTable = {};
local Auto_Save_Intreval = 600;
--// Functions \\--
local function loadStarterData(Player)
local PlayerFolder = game.ServerStorage.Players:WaitForChild(Player.Name)
local Stats = PlayerFolder.Settings
for statname, statvalue in pairs(Data) do
if typeof(statvalue) == "number" then
for i,v in pairs (Stats:GetDescendants())do
if v:IsA("NumberValue") then
if v.Name == statname then
v.Value = statvalue
end
end
end
end
end
end
local function loadData(Player)
local success, err = pcall(function()
Data = DataStore:GetAsync("UserId:"..Player.UserId)
end)
if success then
-- print("Getting "..Player.Name.."'s data was successful!")
else
warn("Something went wrong when retrieving"..Player.Name.."'s data.")
end
local PlayerFolder = game.ServerStorage.Players:WaitForChild(Player.Name)
local Stats = PlayerFolder.Settings
local Data = DataStore:GetAsync("UserId:"..Player.UserId)
if Data then
for statname,statvalue in pairs(Data) do
for i,v in pairs (Stats:GetDescendants())do
if v:IsA("NumberValue") then
if v.Name == statname then
v.Value = statvalue
end
end
end
end
-- print(Player.Name.. "'s data has been loaded!")
else
print(Player.Name.. " has no data! Generating new data.")
end
end
local function saveData(Player)
local PlayerFolder = game.ServerStorage.Players:WaitForChild(Player.Name)
local Stats = PlayerFolder.Settings
if RunService:IsStudio()then return end
local Data = {}
for _,stat in pairs(Stats:GetDescendants())do
if stat:IsA("Folder")then
else
Data[stat.Name] = stat.Value
end
end
local success,err = pcall(function()
DataStore:SetAsync("UserId:"..Player.UserId, Data)
end)
if success then
print(Player.Name.."'s data has been successfully saved!")
else
warn("Something went wrong while saving "..Player.Name.."'s data!")
end
end
Players.PlayerAdded:Connect(function(Player)
SaveTable[Player] = tick()
loadStarterData(Player)
loadData(Player)
end)
Players.PlayerRemoving:Connect(function(Player)
saveData(Player)
end)
game:BindToClose(function()
for _,Player in ipairs(Players:GetPlayers())do
saveData(Player)
end
end)
while true do
wait(1)
for _, Player in pairs(Players:GetPlayers())do
if tick() - SaveTable[Player] >= Auto_Save_Intreval then
saveData(Player)
SaveTable[Player] = tick()
else
end
end
end