I want to put a part into every model using Instance:GetChildren()

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to put a part into every model using Instance:GetChildren()
  2. What is the issue? Include screenshots / videos if possible!
    It doesn’t put the part in every model, just only 1.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
local children = script.Parent:GetChildren()
local part = Instance.new("Part")
local clone = part:Clone()
for i,v in pairs(children)do
	if v:IsA("Model") then
		clone.Parent = v
	end
end

You only create 1 clone at start, if you move line 3 inside the if block then you will get a new clone on each cycle of the loop.

local children = script.Parent:GetChildren()
local part = Instance.new("Part")

for i,v in pairs(children)do
	if v:IsA("Model") then
		local clone = part:Clone()
		clone.Parent = v
	end
end
3 Likes

Try changing :GetChildren() to :GetDescendants(). That will check every object in the script, not just the direct parents of the script.

1 Like

As both @sjr04 and @Urxpaly45 have said, you’ve got options.

  local children = script.Parent:GetDescendants()
local part = Instance.new("Part")

for i,v in pairs(children)do
	if v:IsA("Model") then
		local clone = part:Clone()
		clone.Parent = v
	end
end

There’s a few reasons for this. Firstly in your original code you declare the clone in global scope. What this means is you get 1 clone in the global scope, and all you end up doing is parenting it multiple times. What Incapaz does is sets the clone to a local scope instead, meaning for EACH PART it will clone the brick and parent it, not make 1 clone and keep reparenting it.

As for Urxpaly45’s suggestion, this only applies if you have models inside of models and want to parent bricks into all of them. GetDescendants is different as it searches ALL children of whatever you ask, and the children of those children, and so on and so fourth. It beats making looping functions to find children of children and such. (Though GetChildren() loops are faster by .0004 milliseconds or something… doesn’t matter in your case).

It works! I was not a really good scripter so I didn’t know much about :GetChildren() and now I know how to use them. :smiley: