How to Add a Newly Generated Part to a Function?

Hi, This is a hard question I’ve been struggling with for a while now. I have a script that waits for you to touch a part, and when you touch it, it generates a new part. What I need to do is for the script to then wait for that new part, and do the function, over and over again.
I typed up this script, but I am not a professional scripter, so feel free to point out my errors. Thank you to anyone that helps

local ModelRed = game.Workspace.RedBase

for _, Part in pairs(ModelRed:GetChildren()) do -- this is the part I'm struggling with, recognizing the new part
	if Part:IsA('Part') then
		Part.Touched:Connect(function()
			local newPart = Instance.new("Part")
			newPart.Parent = game.Workspace.ModelRed
			--? How do I make a touched event for this new Part, that then basically repeats infinitely, for every new part generated? It needs to apply to the new part, and the older parts at the same time, if that makes sense.
		end)
	end
end

Thanks to anyone that can help me, or understands what I am asking. I don’t need a whole script, just a few pointers that could lead me in the right direction.

I feel this could be handled using recursion.
I think you may be best off defining a new function to create these special parts.

e.g.

local function createPart(parent)
    local newPart = Instance.new(“Part”)
    
    newPart.Touched:Connect(function()
        createPart(parent)
    end)

    newPart.Parent = parent
end

You then can just use this function in your loop to produce the desired behaviour

1 Like

Okay, thank you! I’m pretty new to scripting, so I struggle with these small technical things. I’ll try it!

1 Like

Worked perfectly, thanks for all of your help!

1 Like