Hi, I have a script where I want it to save the player’s team whenever they leave.
For example if they were on green and left, when they rejoined they would still be on green.
However, when I leave and rejoin, it still keeps teleporting me to lobby team, and I have no idea why.
Could anyone please help?
local dss = game:GetService("DataStoreService")
local deathData = dss:GetDataStore("deathData")
local teamData = dss:GetDataStore("teamData")
game.Players.PlayerAdded:Connect(function(plr)
local lb = Instance.new("Folder", plr)
lb.Name = "leaderstats"
local deaths = Instance.new("IntValue", lb)
deaths.Name = "Deaths"
local death
local succ, err = pcall(function()
death = deathData:GetAsync(plr.UserId.."-deaths")
end)
if succ and death ~= nil then
deaths.Value = death
else
deaths.Value = 0
warn("Error with getting deaths: " .. err)
end
local savedTeamName
local teamSuccess, teamErr = pcall(function()
savedTeamName = teamData:GetAsync(plr.UserId.."-team")
end)
if teamSuccess and savedTeamName then
local savedTeam = game.Teams:FindFirstChild(savedTeamName)
if savedTeam then
plr.Team = savedTeam
print("Restored team for player " .. plr.Name .. ": " .. savedTeamName)
else
plr.Team = game.Teams.Lobby
print("Saved team not found, assigning player to Lobby.")
end
else
plr.Team = game.Teams.Lobby
print("No saved team found, assigning player to Lobby.")
end
plr.CharacterAdded:Connect(function(char)
local teamName = plr.Team and plr.Team.Name
if teamName then
for _, checkpoint in pairs(workspace:FindFirstChild("Checkpoints"):GetChildren()) do
if checkpoint.Name == teamName then
local hrp = char:FindFirstChild("HumanoidRootPart")
if hrp then
hrp.CFrame = checkpoint.CFrame + Vector3.new(0, 2, 0)
print("Teleported player to checkpoint: " .. checkpoint.Name)
end
end
end
end
end)
end)
game.Players.PlayerRemoving:Connect(function(plr)
-- Save deaths
local succ, err = pcall(function()
deathData:SetAsync(plr.UserId.."-deaths", plr.leaderstats.Deaths.Value)
end)
if succ then
print("Deaths successfully saved for player " .. plr.Name)
else
warn("Error with saving deaths: " .. err)
end
-- Save player's team
if plr.Team then
local teamSucc, teamErr = pcall(function()
teamData:SetAsync(plr.UserId.."-team", plr.Team.Name)
end)
if teamSucc then
print("Team successfully saved for player " .. plr.Name)
else
warn("Error with saving team: " .. teamErr)
end
end
end)