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