Having trouble finding descendants of players Character

[Beginner Question]

Hey all, so in my code I am trying to make it so that when a player joins and character is added. It goes through the characters descendants and if it detects an Accessory or a hat then it deletes the Accessories.

Any advice or example code would be helpful.

local playerService = game:GetService("Players")

playerService.PlayerAdded:Connect(function(player)
	if player then
		player.CharacterAdded:Connect(function(character)
			local object = character:GetDescendants()
			for i, ob in pairs(object) do
				if ob:IsA("Accessory") or ob:IsA("Hat") then
					print("Found Accessory")
					ob:Destroy()
				end
			end
		end)
	end		
end)
1 Like

local object = character:GetDescendants() is unnecessary.
You can just put pairs(character:GetDescendants())

Could you add a task.wait() before getting the descendants? Maybe the character hasn’t fully loaded yet.

This line of code is not necessary, remove it.

1 Like

I don’t think you need to GetDescendants, GetChildren should do.

also I would recommend doing

local playerService = game:GetService("Players")

playerService.PlayerAdded:Connect(function(player)

    local charAdded(character)
-- Code for character added here
    end

    if player.Character then
       charAdded(player.Character)
    end

    player.CharacterAdded:Connect(charAdded)
end)
2 Likes

You don’t need local playerService.

game:GetService("Players").PlayerAdded:Connect(function(player)

    local charAdded(character)
-- Code for character added here
    end

    if player.Character then
       charAdded(player.Character)
    end

    player.CharacterAdded:Connect(charAdded)
end)
1 Like

I know I was just copying the code he already wrote.
While you’re at it just do game.Players… lol

1 Like

Well looks like the issue is solved for him lol

Btw I forgot to ask. Why do you recommend writing in that way? Is it just for readability? Because in my last code I rewrote it and it works just fine now but tbh I understood my code better than the one you gave to me. Could you maybe elaborate?

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