Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to add Touched events to a entire model using one script? (Answered)

Asked by
Necrorave 560 Moderation Voter
10 years ago

I am attempting to make one script that takes all the parts in its parent model and give them the ability to kill a player on touch.

Here is what I have...

parts = script.Parent:getChildren()

function onTouch(part)
if part.Parent:FindFirstChild("Humanoid") ~= nil then
part.Parent.Torso:BreakJoints()
end
end

while true do
for x = 0, #parts,1 do
    parts[x].Touched:connect(onTouch)
end
end

Error: 00:20:12.146 - Workspace.Dog.Death:11: attempt to index field '?' (a nil value)

I am curious if I should proceed in a new direction in doing this. I would rather not copy and paste one script in every individual part. I feel this would just make it easier if it can be done.

In general, I would just like to know how to attach Touched events on every part in a single model with one script.

Thanks! :)

1 answer

Log in to vote
2
Answered by
Lacryma 548 Moderation Voter
10 years ago

You need to loop through, find all the objects that have this event and connect it. I also fixed the other errors you had.

parts = script.Parent:GetChildren()

function onTouch(part)
if part.Parent:FindFirstChild("Humanoid") ~= nil then
part.Parent::BreakJoints()
end
end

for i,v in pairs(parts) do
if v:IsA("BasePart") then
v.Touched:connect(onTouch)
end
end
0
Ah, yes. I forgot to add in parameter of what ClassName it should avoid. Sweet, thank you. (Also, just because I am used to "vanilla loops" I am going to avoid the "In pairs" part. I appreciate it though. Necrorave 560 — 10y
0
Also, I forgot that Lua starts indexes at 1, not 0. Thanks again! Necrorave 560 — 10y
Ad

Answer this question