So what I attempted to do is have a character earn currency which puts them on a different team. For example, if a player earned 100 cash they would be on a team called Club 100 and so on. I already have the currency saved but what I learned was that when a player leaves a sever and joins again, they spawn back at Club 0. How can I use datastore to save what Team the player is on?
✓ ANSWER ACCEPTED
How do I save what Team a player is on?
1 answer
✓ Accepted answer
Use DataStore silly :
local DataStoreService = game:GetService(“DataStoreService”)
local DataStore = DataStoreService(“DataStore”) -- Name this whatever you want
local function loadStarterData(Player) -- Basically this is the function that creates the stats
local leaderstats = Instance.new(“Folder”)
leaderstats.Name = “leaderstats”
leaderstats.Parent = Player
local Cash = Instance.new(“IntValue”)
Cash.Name = “Cash” -- Name your currency
Cash.Parent = leaderstats
end
local function loadData(Player) -- Function that loads the data
local Data
local s,e pcall(function()
Data = DataStore:GetAsync(“UserId:”.. Player.UserId)
end)
if s then
Player.leaderstats.Cash.Value = Data[1]
Player.Team = game.Teams[Data[1]]
print(“Loaded ”.. Player.Name ..”’s data successfully”)
else
print(“Failed to load ”.. Player.Name ..”’s data”)
end
end
local function saveData(Player) -- Function that saves the data
local Data = {
Cash = 0,
Team = “”
}
Data.Cash = Player.leaderstats.Cash.Value
Team = Player.Team.Name
local s,e pcall(function()
DataStore:SetAsync(“UserId:”.. Player.UserId, Data)
end)
if s then
print(“Saved ”.. Player.Name ..”’s data successfully”)
else
print(“Failed to save ”.. Player.Name ..”’s data”)
end
end
game.Players.PlayerAdded:Connect(function(Player)
loadStarterData(Player)
loadData(Player)
end)
game.Players.PlayerRemoving:Connect(function(Player)
saveData(Player)
end)
This discussion is preserved as it was. New answers, comments, and votes are closed.

8 comments
I feel like this is pretty complex, make sure to check everytime when the cash.value has changed to change the team
Nice example. But you didn't explain it. If you don't "really" help them, then they will keep coming for more code. And they will not learn something only copy and paste. :/ [It's just my opinion]
Ok basically SetAsync() is what saves the data and GetAsync() is what loads the data you can go check more in the roblox wiki since I’m too lazy to explain in general
On line 2 you forgot to put :GetDataStore()
^ He’s right tho
So I implemented your method of saving the teams into my existing code but I got a weird error that I can't fix. It seems like a simple one but I'm bad at debugging so I'm just going to ask for assistance. The code is
What is the error?
The error is " 'Team' is only used in the enclosing function; consider changing it to local". It's on line 25 of the code I sent as an answer cause it's the only way I know how too show it to you