When multiple players join my game, it generates a bunch of errors and basically breaks my game.
Here is a screenshot:Roblox 09_07_2020 20_49_00 (2)|690x450
Could you guys check my code and help me?
Here is the code:
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")
local DataStore = DataStoreService:GetDataStore('youtubetutorialv:02')
--// Settings \\--
local StarterData = {
Kills = 0;
Slashes = 0;
Cash = 0;
};
local playersavetable = {};
local AUTO_SAVE_INTERVAL = 180; -- time when the game auto saves
--// Functions \\--
local function loadStarterData(Player) -- loading the starter data
local Stats = Instance.new("Folder")
Stats.Name = 'leaderstats'
Stats.Parent = Player
for statname, statvalue in pairs(StarterData) do
if type(statvalue) == "number" then
local numbervalue = Instance.new("NumberValue")
numbervalue.Name = statname
numbervalue.Value = statvalue
numbervalue.Parent = Stats
elseif type(statvalue) == 'boolean' then
elseif type(statvalue) == 'string' then
end
end
end
local function loadData(Player)-- Loading saved data
local Data
local s, e = pcall(function()
Data = DataStore:GetAsync('UserId'..Player.UserId)
end)
if s then
print('Getting '..Player.Name.."'s data was for the main leaderstats successful")
else
warn('something went wrong when loading'..Player.Name.."'s data")
end
if Data then
for statname, statvalue in pairs(Data) do
Player.leaderstats[statname].Value = statvalue
end
print(Player.Name.."'s main leaderstats data has been loaded!")
else
print(Player.Name..' has no main leaderstats data! Generating new data')
end
end
local function saveData(Player)-- Saving data
if RunService:IsStudio() then return end
local Data = {}
for _, stat in pairs(Player.leaderstats:GetChildren()) do
Data[stat.Name] = stat.Value
end
local s, e = pcall(function()
DataStore:SetAsync('UserId'..Player.UserId, Data)
end)
if s then
print(Player.Name.."'s data has been successfuly saved")
else
warn('Something went wrong while saving '..Player.Name.." 's data")
end
end
Players.PlayerAdded:Connect(function(player)-- loading the data when the player joins
playersavetable[player] = tick()
loadStarterData(player)
loadData(player)
end)
Players.PlayerRemoving:Connect(function(player) -- saving the data when a player quits the game
saveData(player)
end)
while true do
wait(1)
for _, player in pairs(Players:GetPlayers()) do
if tick() - playersavetable[player] >= AUTO_SAVE_INTERVAL then
saveData(player)
playersavetable[player] = tick()
end
end
end