Need help converting these scripts into one script by CollectionService

I’ve read the post on the Community Tutorials “Collection Service in a nutshell”

by @flamenco_687 and I kinda understand on what he meant of looping
through tagged parts and adding a function to em but now I’m having problems of converting a meteor script into CollectionService so I won’t have to duplicate the script and paste into the part so heres the code

local c = game:GetService("CollectionService")
for _, i in pairs(c:GetTagged("Meteorite")) do
function OnTouch()
				local e ="Explosion")
				local CEP = game:GetService("ServerStorage").CustomExplosionP:Clone()
				CEP.Parent = workspace
				CEP.Position = i.Position
				e.BlastPressure = 2800000
				e.BlastRadius = 85
				e.Parent = workspace
				e.Position = i.Position
				--If you want to add sound on explosion
				local Bsound ="Sound")
				Bsound.SoundId = "rbxassetid://440431180"
				Bsound.Volume = 4
				Bsound.PlaybackSpeed = 0.8 
				Bsound.PlayOnRemove = true 
				Bsound.Parent = i
	i.Position =,2000),math.random(850,1000),math.random(-2000,2000))
	i.BP.Position =,500),-1,math.random(-500,500))
		if (p.CanCollide == true) then -- kinda out of topic but when do i use these brackets in the future of making another if statement? Tried it without the brackets and nothing changed 
			OnTouch() -- somehow the function doesnt run when i called it :/

Any help?

1 Like

Move the OnTouch function out of the loop, and ensure it has the parameter i, function OnTouch( i ).

Inside your loop, when you call OnTouch inside the Touched event callback, pass i as an argument,

if p.CanCollide then
    OnTouch( i )

Your function is the same for every meteorite so it doesn’t need to be redefined with each meteorite. Having it as 1 function with the ability to specify which meteorite you want it to act on is the better way to approach this.


Thanks! just one more question but out of topic, i put

if (p.CanCollide == true) then

i made it with brackets but without brackets nothing happened so when
will i use brackets for an if statement in the future?

With and without makes no difference when it’s 1 statement.

Sometimes you might end up in a complicated situation where you have multiple, and then it’s easier to put brackets than worry about the order in which they’re resolved.