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 = Instance.new("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 = Instance.new("Sound")
				Bsound.SoundId = "rbxassetid://440431180"
				Bsound.Volume = 4
				Bsound.PlaybackSpeed = 0.8 
				Bsound.PlayOnRemove = true 
				Bsound.Parent = i
				i:Destroy()
			end
	i.Position = Vector3.new(math.random(-2000,2000),math.random(850,1000),math.random(-2000,2000))
	i.BP.Position = Vector3.new(math.random(-500,500),-1,math.random(-500,500))
	i.Touched:Connect(function(p)
		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 :/
		end
	end)
end

Any help?

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 )
end

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.

4 Likes

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

if (p.CanCollide == true) then
end

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.

2 Likes