Hello there, So Im making a DataStore but when I leave and rejoin it isn’t working, This is my script:
local DataStoreService = game:GetService("DataStoreService")
local DataStoreMain = DataStoreService:GetDataStore("DataMain")
game.Players.PlayerAdded:Connect(function(Player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = Player
local Kills = Instance.new("IntValue")
Kills.Name = "Kills"
Kills.Value = 0
Kills.Parent = leaderstats
local KDR = Instance.new("IntValue")
KDR.Name = "KDR"
KDR.Value = 0
KDR.Parent = Player
local Deaths = Instance.new("IntValue")
Deaths.Name = "Deaths"
Deaths.Value = 0
Deaths.Parent = Player
local Credits = Instance.new("IntValue")
Credits.Name = "Credits"
Credits.Value = 0
Credits.Parent = leaderstats
local XP = Instance.new("IntValue")
XP.Name = "XP"
XP.Value = 0
XP.Parent = Player
local Rank = Instance.new("StringValue")
Rank.Name = "Rank"
Rank.Value = ""
Rank.Parent = leaderstats
local Tries = 0
local Data
local success, err = pcall(function()
Data = DataStoreMain:GetAsync(Player.UserId)
end)
if success then
print("Got Data!")
else
print("Player has no data, New.")
end
if err then
print(err)
print("Coulden't get Data, Retrying...")
Data = DataStoreMain:GetAsync(Player.UserId)
Tries = Tries + 1
end
end)
game.Players.PlayerRemoving:Connect(function(Player)
local success, err = pcall(function()
DataStoreMain:SetAsync(Player.UserId, Player.leaderstats.Kills.Value)
DataStoreMain:SetAsync(Player.UserId, Player.KDR.Value)
DataStoreMain:SetAsync(Player.UserId, Player.Deaths.Value)
DataStoreMain:SetAsync(Player.UserId, Player.leaderstats.Credits.Value)
DataStoreMain:SetAsync(Player.UserId, Player.XP.Value)
DataStoreMain:SetAsync(Player.UserId, Player.leaderstats.Rank.Value)
end)
if success then
print("Successfully saved data!")
end
if err then
print("Coulden't save Data!")
print(err)
end
end)
game:BindToClose(function()
for _, v in pairs(game.Players:GetPlayers()) do
print("Shutting down server")
end
wait(5)
end)
I tried adding the tries counter so if it errors it will print Coulden’t get Data.
If success is false that doesn’t mean that the player has no data. Success will be false if there is an error in the code. If Data is nil and Success is true the player has no data.