✓ Accepted answer
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
local DataStore = DataStoreService:GetDataStore("DataStoreV"..DataStoreVersion)
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.
2 comments
Sorry for the late reply, but i appreciate you making this for me, i will try my best to study what you did so i can know for the future.
the pcall function is used in this code so the script doesnt stop completely if there is an error loading stats, if the pcall function which is assigned to load or save player data succeeds then it will change the player stats to the loaded data, if there is an error it will print it in the output bar or developer console and not stop the script