Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I go through models efficiently without for loops?

I have a model and inside that models is four more models and inside those models are bricks , and inside some of the bricks have clickDetectors, now I could just put a script in each clickDetector but I don't find the efficient. How could I make all clickDetectors work on one single script without having to do like three for loops?

I tried this, it works, but I don't think its very efficient.

for i,v in pairs(workspace.Mannequins:GetChildren()) do
	for d,g in pairs(v:GetChildren()) do
		for p,n in pairs(g:GetChildren()) do
			--code
		end
	end
end

I would do this on the client and use player.Mouse.Target, but I wish to keep this code on the server to it can't get stolen (FE is ON)

3 comments

0

If you know the names of each of the clickdetectors, then just use workspace.Mannequins:FindFirstChild("ClickDetector", true)

0

I won't becuase eventually there will be around 100-200 models inside that one main model.

0

you could make a module script. return what mannequins click, and do the actions you need to do. but since you said you're making 100-200, you might not feel like making 100-200 scripts calling 1 module script :P

1 answer

Here you could use a recursive function, there is some useful info about it on the roblox wiki here.

Here is the code you could use:

function findDescendants(parent)
	for i, v in pairs(parent:GetChildren()) do
		if v:IsA("Part") then
			if v:findFirstChild("ClickDetector") then -- make sure the name here matches the  name of the clickdetector under the parts
				v.ClickDetector.MouseClick:connect(function()
					-- what it should do when it is clicked
				end)
			end
		elseif v:IsA("Model") then
			findDescendants(v)
		end
	end
end

findDescendants(workspace.Mannequin) -- refer to the first model

Hope this helped! If you have any questions please do not hesitate to let me know.

This discussion is preserved as it was. New answers, comments, and votes are closed.