Hello, So I'm making a game and I was wondering how can I add so my kills stat would save. I already added it so I just need the save thingy. The problem is that a guy on here gave me this script and I don't really understand it that much.
My code:
local DataStoreService = game:GetService("DataStoreService") local CashDS = DataStoreService:GetDataStore("Cash") local RS = game:GetService("RunService") game.Players.PlayerAdded:Connect(function(plr) local Cash = Instance.new("IntValue") Cash.Name = "Cash" Cash.Parent = plr Cash.Value = 0 local Kills = Instance.new("IntValue") Kills.Name = "Kills" Kills.Parent = plr Kills.Value = 0 local data local g, err = pcall(function() data = CashDS:GetAsync("cash_"..plr.UserId) end) if not g then warn(err) else if data ~= nil then Cash.Value = data end end end) game:BindToClose(function() if RS:IsStudio() then return end local plrs = game.Players:GetPlayers() for _, plr in pairs(plrs) do local data = plr.Cash.Value if plr:FindFirstChild("TagValue") then data -= 50 end if data then local g, err = pcall(function() CashDS:UpdateAsync("cash_"..plr.UserId, function(old) local new = old or 0 new = data return new end) end) if not g then warn(err) end end end end) game.Players.PlayerRemoving:Connect(function(plr) local data = plr.Cash.Value if plr:FindFirstChild("TagValue") then data -= 50 end if data then local g, err = pcall(function() CashDS:UpdateAsync("cash_"..plr.UserId, function(old) local new = old or 0 new = data return new end) end) if not g then warn(err) end end end)
These leaderstats are good but there are better ones that use NumberValues as leaderstats, and it's so much easier to add more of them and it goes up to even infinite amounts of leaderstat names! Simply put this script inside of ServerScriptService and put NumberValues inside of it. Make sure the values are named after the leaderstats u want in ur game. Only one of the leaderstats will work inside of Studio, normally they all work, so u should probably make a testing place if u dont have one already. Hope this helped!
game.Players.PlayerAdded:connect(function(player) local DataStore = game:GetService("DataStoreService") local leader = Instance.new("Folder",player) leader.Name = "leaderstats" for i,v in pairs(script:GetChildren()) do local d = DataStore:GetDataStore(v.Name) local x = Instance.new("NumberValue",leader) x.Name = v.Name x.Value = d:GetAsync(player.UserId) or v.Value end end) game.Players.PlayerRemoving:Connect(function(player) for i,v in pairs(script:GetChildren()) do print("Getting") local DataStore = game:GetService("DataStoreService") local d = DataStore:GetDataStore(v.Name) d:SetAsync(player.UserId, player.leaderstats[v.Name].Value) print("Saved") end end)