In a few of my games, I use datastores to save progress. The only problem is, in order to load your data, you need to get more of that value (For example, if your kills in a game were saved, you would need to get another kill for the data to load.)
This is the code for my script, in this instance, the value is “Cash”
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("DataStoreValues") --Name the DataStore whatever you want
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local Cash = Instance.new('NumberValue', leaderstats)
Cash.Name = "Cash"
Cash.Value = 0
local value1Data = Cash
local s, e = pcall(function()
value1Data = DataStore:GetAsync(player.UserId.."-Value1") or 0 --check if they have data, if not it'll be "0"
end)
if s then
Cash.Value = value1Data --setting data if its success
else
game:GetService("TestService"):Error(e) --if not success then we error it to the console
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local s, e = pcall(function()
DataStore:SetAsync(player.UserId.."-Value1", player.leaderstats.Cash.Value) --setting data
end)
if not s then game:GetService("TestService"):Error(e)
end
end)