Help with ":GetChildren()" through several models at once?

  1. What do you want to achieve?
    I want my train driving script to find all of the parts named “Engine” across an entire model, even if they’re in several “sub-models”, whatever they’re called.

  2. What is the issue?
    The script currently only serves one vehicle at a time, in this case, the locomotive. It uses :GetChildren() to find all of the parts named “Engine” (these parts are what make the vehicle move), but only if they’re in the same model / parent as the control script.

  3. What solutions have you tried so far?
    None yet. I’m baffled.

Screenshot_2

Above is a quick example of how the script currently works. It does see the Engine parts, as the script is in the same parent as them.


Screenshot_1

In this above image, this is how I want the Engine parts sorted. The script no longer sees the Engine parts, thus the train will not move. “Front” is the locomotive (temporary name). “Model” is intended to be the whole train itself – the locomotive and whatever amount of cars is trailing with it.

Putting all of the Engine parts in the same parent as the script is both impractical and inefficient. I can’t just do “script.Parent.Front.BogieF.Engine” because there’s going to be several of the “BogieF”, “BogieR,” and “Engine” parts in the locomotive and the cars.


bin = script.Parent
function GetEngines() -- This finds all the engines in the train and then puts them into the table 'EngTable'.
	for _, a in pairs(bin:GetChildren()) do
		if (a.Name == "Engine") then
			-- if a:findFirstChild("BodyVelocity") then
			local bv = script.BodyVelocity:Clone()
			bv.Parent = a
			EngTable[#EngTable + 1] = a
			-- end
		end
	end
end 
bin = script.Parent
function GetEngines() -- This finds all the engines in the train and then puts them into the table 'EngTable'.
	for _, a in pairs(bin:GetDescendants()) do -- gets **everything**
		if (a.Name == "Engine") then
			-- if a:findFirstChild("BodyVelocity") then
			local bv = script.BodyVelocity:Clone()
			bv.Parent = a
			EngTable[#EngTable + 1] = a
			-- end
		end
	end
end 
2 Likes

Use GetDescendents() is it exactly what you want

2 Likes

Both you, @Thigbr, and @HugeCoolboy2007’s replies did just the trick! And so fast, too! Thanks!

(I don’t know which one to mark as the solution. ;~;)

GetDescendants Is very unique, GetChildren just gets every child that’s the parent of the Child you called the GetChildren() on, GetDescendants gets every child that’s inside of that specific model. So what he did was change

for _, a in pairs(bin:GetChildren()) do

to

for _, a in pairs(bin:GetDescendants()) do

Hope that clears some stuff up for you!

1 Like

I accidentally replied to your reply instead of a private message! I’m on mobile, so the page layout is especially awkward!

1 Like