Code for handing player joins/leaves keeps failing

In my game, I have a serverscript in ServerScriptService that fires events based off when a player joins and leaves. For the purposes of my game, it first sets the player’s collision group and gives them a folder in workspace, and then once they leave, that folder is then removed.
(Each player has a folder that contains vehicles they may spawn.)

Problem is, it just stops working? I can’t determine when or how it stops working, because when a server initially begins it appears to be fine.
Just compare this image of the leaderboard to the explorer-menu I have up. There should only be 7 player folders in there ( not counting debris), not way more.

Here is the code:

local players = game:GetService(“Players”)
local function setPlayerCollisionGroup(character)
for _, part in character:GetChildren() do
if part:IsA(“BasePart”) then
part.CollisionGroup = “Players”
end
end
end

players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
setPlayerCollisionGroup(character)
local folder = Instance.new(“Folder”)
folder.Name = player.Name
folder.Parent = workspace:WaitForChild(“TrainFolder”)
end)
end)

players.PlayerRemoving:Connect(function(player)
local targetFolder = workspace.TrainFolder:FindFirstChild(player.Name)
if targetFolder then
targetFolder:Destroy()
end
end)

for _, player in players:GetPlayers() do
if player.Character then
setPlayerCollisionGroup(player.Character)
end
end

Any help is appreciated, thank you!

When putting code in your post, please surround it by ```, so it is formatted :slight_smile:

Anyway, the issue with your code is that you are creating the folder each time the player respawns. Then, when they leave, you are only removing one copy of the folder. You can try listening to the Humanoid.Died event, or you can check for an existing folder when the player’s character is added.

e.g.

local TrainFolder = workspace:WaitForChild("TrainFolder")
players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		setPlayerCollisionGroup(character)
		if not TrainFolder:FindFirstChild(player.Name) then
			local folder = Instance.new(“Folder”)
			folder.Name = player.Name
			folder.Parent = TrainFolder 
		end
	end)
end)

Alternatively, you could just move the folder code outside of the character added event:

local TrainFolder = workspace:WaitForChild("TrainFolder")
players.PlayerAdded:Connect(function(player)
	local folder = Instance.new(“Folder”)
	folder.Name = player.Name
	folder.Parent = TrainFolder 

	player.CharacterAdded:Connect(function(character)
		setPlayerCollisionGroup(character)
	end)
end)

Thank you! This makes sense. I previously didn’t realize that the folders regenerated each time a player simply spawned.