I have a small question regarding leaderstats in Roblox.
I have a small but nice game in Roblox only one really annoying problem. Whenever I add a new thing in the game at Roblox Studio then and then publish then all who come in the game have the same stats in the leaderstats. I just can not find the problem I hope someone could help me?
My leaderstats script:
local DataStoreService = game:GetService(“DataStoreService”)
local ds1 = DataStoreService:GetDataStore(“CashSave”)
local ds2 = DataStoreService:GetDataStore(“KillSave”)
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new(“Folder”, player)
leaderstats.Name = “leaderstats”
local Cash = Instance.new(“IntValue”, leaderstats)
Cash.Name = “Cash”
local kill = Instance.new(“IntValue”, leaderstats)
kill.Name = “Kills”
wait()
Cash.Value = ds1:GetAsync(player.UserId) or 0
ds1:SetAsync(player.UserId, Cash.Value)
kill.Value = ds2:GetAsync(player.UserId) or 0
ds2:SetAsync(player.UserId, kill.Value)
local playerRemoving = function(plr)
ds1:SetAsync(plr.UserId, Cash.Value)
ds2:SetAsync(plr.UserId, kill.Value)
end
game.Players.PlayerRemoving:Connect(playerRemoving)
You aren’t encasing your DataStore functions in pcalls, which is more than likely the reason why your data keeps failing to load
Simply, a pcall is a protective call to prevent the script from breaking & resulting as a warning rather than an error if it fails to load the data
local DataStoreService = game:GetService("DataStoreService")
local ds1 = DataStoreService:GetDataStore("CashSave")
local ds2 = DataStoreService:GetDataStore("KillSave")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local Cash = Instance.new("IntValue", leaderstats)
Cash.Name = "Cash"
local kill = Instance.new("IntValue", leaderstats)
kill.Name = "Kills"
local Data
local Data2
local success, whoops = pcall(function()
Data = ds1:GetAsync(player.UserId)
Data2 = ds2:GetAsync(player.UserId)
end)
if success and Data and Data2 then
print("Loaded data successfully!")
Cash.Value = Data
kill.Value = Data2
else
Cash.Value = 0
Kill.Value = 0
warn("An error occured trying to loading the data. Error:", whoops)
end
end)
local function playerRemoving(plr)
local success, whoops = pcall(function()
ds1:SetAsync(plr.UserId, plr.leaderstats.Cash.Value)
ds2:SetAsync(plr.UserId, plr.leaderstats.Kills.Value)
end)
if success then
print("Data saved successfully")
else
print("An error occured retreiving the data")
end
end
game.Players.PlayerRemoving:Connect(playerRemoving)
I’m too lazy to do the rest but you can try that, also make sure that API Services are enabled