Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do refer to all parts in an entire model in a script?

I would like the wedge to be replaced with all the parts which are in a model. How could i refer to multiple parts in a model?

local toggle = false
local ForceStop = -50
local StartForce = -5000

script.Parent.Wedge.Touched:connect(function(hitPart)
 if toggle == false then
 toggle = true
if hitPart == game.Workspace.Block or hitPart.Parent:FindFirstChild('Humanoid')then  
local force = Instance.new("BodyForce")
force.Parent = hitPart
for i = 1,100 do
	force.Force = Vector3.new(0,0,StartForce)-Vector3.new(0,0,i*ForceStop)
	wait(0.01)
end
end
end
end)

script.Parent.TouchEnded:connect(function(hitPart)
if hitPart:FindFirstChild('BodyForce') then
	hitPart.BodyForce:Destroy()
end
toggle = false
end)

1 comment

0

use for loop and get each child

2 answers

✓ Accepted answer

Just simply use :GetChildren(), like this: (Unrecommended)

local AllOfTheParts = Model:GetChildren()

Or this: (Recommended)

for i,v in pairs(Model:GetChildren()) do
      --Your code here, v is the reference of all the parts inside of the model.
      --Example code:
      --[[
           local BodyForce = Instance.new("BodyForce")
           BodyForce.Parent = v
      --]]
      --You don't have to do anything else, just treat v like a single part, the for loop will run the code for all of the objects found in the model.
end

1 comment

0

Thank you

So, in this case, we are not exactly sure if there are more children inside this Model and if there are other Model's inside this model so we should be using :GetDecendants().

**What is the difference between :GetDecendants() and :GetChildren()? **

:GetChildren() get's the Children of an object regardless of if there are more children inside those children's meaning that if there are more parts inside parts or parts inside models, it wouldn't get that.

:GetDecendants() on the other hand, get's every single Instance inside the object you are referring to. This is more recommended in this case to be safer since we are not sure if it's really all parts.

So:

for _, Instance in pairs(YourModel:GetDecendants()) do
	if Instance:IsA('BasePart') then
		-- do something note that Instance is every part so you do it to Instance you do it to all
	end
end

As you can see, I used :IsA() to separate and group each item individually, this way, only Parts will be affected.

Hopefully, this helped you.

Best of luck developer!

1 comment

0

You shouldn’t of called the variable Instance, as this can override the globa variable for the table, Instance.

This discussion is preserved as it was. New answers, comments, and votes are closed.