Check if object has a child in it?

So I have this part of my code, where im trying to change the color of a hair, and if the hair has a child named “Prop” in it, to change the prop color with the regfular hair, how do I do this and make it work.

					a.Handle.BrickColor = realcolor
					for _,v in pairs(game.ReplicatedStorage.FakeHairs:GetChildren()) do
					if v.Name == "Prop" then
					a.Handle.Prop.BrickColor = realcolor
					else
					end
					end
					end
	end
	end
	end

I can offer you two ways to accomplish this. If you want to simply check and see if a certain object is inside of another object, you can use the FindFirstChild method, like so:

local hair = v:FindFirstChild("Prop")

If it finds an object named “Prop”, it’ll return the object to the hair variable.

If you desire to determine if there’s any object inside of another object, you can use this line:

local is_another_object = #v:GetChildren() > 0

That line of code will return true if the number of objects inside of specified object is greater than 0.

Hope this helps!

14 Likes

First of all use ipairs,
that’s much faster and that is used when iterating over pairs of keys and values is not necessary

Like:

for _,hair in ipairs(game.ReplicatedStorage.FakeHairs:GetChildren()) do
    --this should contain the 'hairs'
    --each hair thing should be a model, each should be called prop
    local handle = workspace.handle
    hair.Handle.Prop.BrickColor = BrickColor.new(handle.Handle.BrickColor)
end

-- to see whether something has children do this
local toBeCounted =  game.ReplicatedStorage.FakeHairs:GetChildren()
local count = #toBeCounted

if count>someAmount then 
    -- do something
end
1 Like

Welcome to micro-optimization land! If you are optimizing code that would never have performance problems in the first place, then you have gone too far. It is okay to optimize a loop that is run a million times a second and impacting performance, as the micro-optimizations will accumulate into something meaningful, but if you are tailoring anything else and going from 0.0012 milliseconds to 0.0011 milliseconds, then you have wasted your time. The orientation of the moon and the sun have more impact on your game’s performance.

Do not optimize arbitrary code for the sake of optimization – you are wasting your time and making it more complicated with no benefit. Only optimize if there is a real performance problem.

33 Likes