How to make one script act on several parts?

Greetings dear developers!

I have a script here that allows one or another part to fall off the model if its health becomes zero… And I would like to know how to make this script act not only on one part, but on several parts at once. That is, so that it is not necessary to multiply this script and put it in each part separately.

Thank you for attention.

And here is the script itself, if you please:

function crashed(hit)
if script.Parent.Velocity.Magnitude > hit.Velocity.Magnitude + 3 and hit.CanCollide == true or hit.Velocity.Magnitude >
script.Parent.Health.Value = script.Parent.Health.Value - script.Parent.Velocity.Magnitude / 1.25
wait ()
if script.Parent.Health.Value <= 100 and script.Parent.Health.Value >= 0 then
–Instance.new(“Fire”,script.Parent)
end
if script.Parent.Health.Value <= 0 then
–local e = Instantce.new(“Explosion”, script.Parent.Parent.Parent)
–e.BlastPressure = 50
–e.BlastRadius = 1
–e.Position = script.Parent.Position

end

if script.Parent.Health.Value > 50 then
script.Parent.Sparks.Enabled = true
local sound = math.random(1, 2)
if sound == 1 then
script.Parent.Collide.SoundId = “rbxassetid://490314550”
end
if sound == 2 then
script.Parent.Collide.SoundId = “rbxassetid://215550851”
end

script.Parent.Collide.Playing = true
wait(0.5)
script.Parent.Sparks.Enabled = false
wait()
script.Disabled = false
else
script.Disabled = true
script.Parent:BreakJoints()
script.Parent.CanCollide = true
script.Parent.Break.Playing = true
script.Parent.Parent = workspace
wait(15)
script.Parent:no()
end
end
end
script.Parent.Touched:Connect (crashed)

Forgive me if there was a mistake somewhere, because I wrote it by hand.

An easy way of doing this would to put them in a folder, and loop through all of them.

for i, v in pairs(Folder:GetChildren()) do 
	v.Touched:Connect(function()
		-- Run your code here
	end)
end 

Another more optimal method is to use CollectionService:

3 Likes

That is pretty much the way since we run on a OOP based system. However if you know a way to implement ECS it speeds the time by like a billion

1 Like

talk normally i cant understand this kek slang

1 Like