I'm very new to scripting, and i was wondering how i can save my leaderstats, here is my script
game.Players.PlayerAdded:Connect(function(player) local leaderstats = Instance.new("Folder",player) leaderstats.Name = "leaderstats"
local cash = Instance.new("IntValue") cash.Name = "Cash" cash.Value = 0 cash.Parent = leaderstats local coin = Instance.new("IntValue") coin.Name = "Coins" coin.Value = 0 coin.Parent = leaderstats local Rebirths = Instance.new("IntValue") Rebirths.Name = "Rebirths" Rebirths.Value = 0 Rebirths.Parent = leaderstats
end)
You can save stats through data stores, replace the whole code of your script with this code:
local DataStoreService = game:GetService("DataStoreService") local DataStoreVersion = 1 -- Changing this version will wipe all data of players local DataStore = DataStoreService:GetDataStore("DataStoreV"..DataStoreVersion) -- Changing "DataStoreV" will also wipe all data of players 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 Coins = Instance.new("IntValue",Leaderstats) Coins.Name = "Coins" local Rebirths = Instance.new("IntValue",Leaderstats) Rebirths.Name = "Rebirths" local loadedcash local loadedcoins local loadedrebirths local success,errormessage = pcall(function() loadedcash = DataStore:GetAsync(Player.UserId.."-Cash") loadedcoins = DataStore:GetAsync(Player.UserId.."-Coins") loadedrebirths = DataStore:GetAsync(Player.UserId.."-Rebirths") end) if success then Cash.Value = loadedcash Coins.Value = loadedcoins Rebirths.Value = loadedrebirths else print("Data load encountered an error,Player Data not loaded") warn(errormessage) end end) game.Players.PlayerRemoving:Connect(function(Player) local success,errormesssage = pcall(function() DataStore:SetAsync(Player.UserId.."-Cash",Player.leaderstats.Cash.Value) DataStore:SetAsync(Player.UserId.."-Coins",Player.leaderstats.Coins.Value) DataStore:SetAsync(Player.UserId.."-Rebirths",Player.leaderstats.Rebirths.Value) end) if success then print("Data Save was successful") else print("Data Save Error Occured, Data not saved") warn(errormesssage) end end)
The code works but you should also learn how to use data stores yourself.