How to skip pass something if it is nil

I have a script that is supposed to detect if a character already has hair. and then deletes that hair if a character chooses to change it. But the script errors and returns nil which makes sense because at the start if the game during character customization the character wont have any hair.

But basically how can I keep the script from running still even if it returns nil.


	local hair3 = {char:FindFirstChild("MaleHair"), char:FindFirstChild("LongStraightHair")}
	
	hair3:Destroy()
local thing = char:FindFirstChild('Hair')


if thing then
  thing:Destroy()
end
if character:FindFirstChild("Hair") then
-- stuff here
end

Both @imNiceBox and @E7LK should work. Basically you just do FindFirstChild cuz if there is hair then it will come back true but it should come back nil if there is no hair which can then be filtered out with a simple if statment.

4 Ways

  • First way
if youritem ~= nil then
-- it's Not nil
end
  • Second way

if youritem == nil then 
-- its nil
else
-- its not nil
end
  • Third way (Best way)
If youritem then
--it's not nil
end
  • Fourth way
if Player.Character:FindFirstChild(hair3) then
 --it's not nil
end

These 3 ways are the same, and will work only when youritem is a value returned by FindFirstChild.

local hair = char:FindFirstChild("MaleHair") or char:FindFirstChild("LongStraightHair") or ...
hair:Destroy()

or

local hairs = {
    char:FindFirstChild("MaleHair"),
    char:FindFirstChild("LongStraightHair"),
    ...
}

for i, hair in hairs do
    hair:Destroy()
end

Yes, I’m telling him there is 3 ways he could do that.

But then when i try to define “hair” it returns a nil value…
@E7LK @LifeDigger @lilmazen1234 @5uphi @imNiceBox

Try somthing like this:

for i,v in pairs(character:GetChildren()) do
	if v:IsA('Accessory') and v.AccessoryType == Enum.AccessoryType.Hair then
		print('this is a hair')
	end
end
1 Like

Well I wasn’t talking about a type of instance, I was talking about an instance named “Hair”, if I was talking about an instance class I would’ve suggested you use FindFirstChildOfClass(). So if you know what the names of the instances will be then use my previously suggested method, else, use @LifeDigger 's method.

1 Like