Deleting multiple team-tools from users inventory

Hello, I’m trying to create a script that reads when a player switches teams it’ll delete or add tools depending on their team selection. I have a folder in ServerStorage that contains multiple tools for a “Police” team that gets added to the player when they join that team but I’m not sure how to find or delete those specific tools from the players backpack if they decide to swap out of that team. I’m a pretty novice scripter so sorry for the ugly code.

local PoliceTools = WeaponsFolder.Police:GetChildren()
local TeamsService = game:GetService("Teams")

for _, team in pairs(TeamsService:GetTeams()) do
	team.PlayerAdded:connect(function(player)
		if player.Team.Name == "Police" then
			for i = 1, #PoliceTools do
				local TeamTools = PoliceTools[i]
				TeamTools:Clone().Parent = player.Backpack
			end
		else
			if player.Team.Name ~= "Police" then 
				for i,v in pairs(player.Backpack:GetChildren()) do -- This is the part that I can't figure out
					if v:GetChildren(PoliceTools) then
						v:Destroy()
					end
				end
			end
		end	
	end)
end

Again, I have no issue getting the tools into the users inventory when they switch to the police team, it’s just deleting those specific tools out of their inventory if they decide to leave the team.

You can try using tags to identify police tools(basically use them as unique identifiers instead of direct checks like name, etc):

local function getPlayerTools(player: Player): {Tool}
	local tools = {}
	for _, tool in pairs(player.Backpack:GetChildren()) do
		if tool:IsA("Tool") then table.insert(tools, tool) end
	end
	if not player.Character then return tools end
	table.insert(tools, player.Character:FindFirstChildWhichIsA("Tool"))
	return tools
end

local function getPlayerToolsWithTag(player: Player, tag: string): {Tool}
	local tools = {}
	for _, tool in pairs(getPlayerTools(player)) do
		if tool:HasTag(tag) then table.insert(tools, tool) end
	end
	return tools
end

local Teams = game:GetService("Teams")

for _, team in pairs(Teams:GetTeams()) do
	team.PlayerAdded:Connect(function(player)
		if player.Team.Name == "Police" then
			for _, tool in pairs(WeaponsFolder.Police:GetChildren()) do
				local new = tool:Clone()
				new:AddTag("Police")
				new.Parent = player.Backpack
			end
		else
			local policeTools = getPlayerToolsWithTag(player, "Police")
			for _, tool in pairs(policeTools) do tool:Destroy() end
		end
	end)
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.