****Why isn't that if statement inside the for loop working?
I've been scripting a while and this code seems to be correct but the if statement is not working I would appreciate if some one could look at it and see if there is a simple mistake I am missing.
local ClothingRemover = coroutine.create(function() local OnChildSpawned = function(obj) print(obj:GetFullName()) if obj:IsA("Model") and obj:FindFirstChild("Humanoid") ~= nil and game.Players:FindFirstChild(obj.Name) ~= nil then for j,k in pairs(obj:GetChildren())do if k:IsA("Shirt") or k:IsA("Pants") or k:IsA("ShirtGraphic") then k:Destroy() end end end end game.Workspace.ChildAdded:connect(OnChildSpawned) end)
Nothing appears to be wrong with the code if as you say is true, and the if statement on line 6
just isn't detecting the clothing.
So the problem isn't with your code, it's just one small overlooked detail. You are trying to detect a descendant of a model immediately after you initially detected the model itself. There is no time for the descendant to fully load! So it is nil when you check it on line 6
.
To fix this, simply add a wait after line 3
. This will yield the code and allow time for the objects to load.
local ClothingRemover = coroutine.create(function() local OnChildSpawned = function(obj) print(obj:GetFullName()) wait(1) --Yield if obj:IsA("Model") and obj:FindFirstChild("Humanoid") ~= nil and game.Players:FindFirstChild(obj.Name) ~= nil then for j,k in pairs(obj:GetChildren())do if k:IsA("Shirt") or k:IsA("Pants") or k:IsA("ShirtGraphic") then k:Destroy() end end end end game.Workspace.ChildAdded:connect(OnChildSpawned) end)
I am unsure as to why all of the code is inside a coroutine.. but I'm positive that it is unneeded. You said in the chat that it was there because you have other code past this that needs to run at the same time.
Rather than supplementing for that fact by using a coroutine, I advise you make a whole new script in the workspace, that consists of a PlayerAdded
event, and a CharacterAdded
event with the same code you used to detect and eradicate all clothing.
--PlayerAdded event game.Players.PlayerAdded:connect(function(plr) --CharacterAdded event plr.CharacterAdded:connect(function(char) --Same code! print(char.Name); --Yield until the torso is detected repeat wait() until char:FindFirstChild("Torso") for j,k in pairs(char:GetChildren())do if k:IsA("Shirt") or k:IsA("Pants") or k:IsA("ShirtGraphic") then k:Destroy() end end end) end)