So I put a script inside of a model, to make all of it’s children clickable, and when they are clicked, I want to get the specific object clicked, and run it through a function. Thanks!
1 Like
You can try something like this.
local function clicked(part, player)
...
end
for i,v in pairs(model:GetChildren()) do
Instance.new("ClickDetector", v).Clicked:Connect(function(p) clicked(v,p) end)
end
2 Likes
A simpler way to do it (at the cost of some readability)
for i,v in pairs(model:GetDescendants()) do --(To go through EVERYTHING in the model)
if v:IsA("ClickDetector") then
v.Clicked:Connect(function(p)
--TODO: yes
--because of scopes you can now just use v.Parent to get the object clicked
--(assuming the clickdetector is the child of a part which it should be)
end)
end
end
2 Likes
One step simpler, if you put the code from lines 6 to 10 in the same loop where you create the ClickDetectors, you can just reference them immediately instead of having to find them again.
for _, part in ipairs(model) do
local cd = Instance.new("ClickDetector")
-- parent and name the ClickDetector
cd.MouseClick:Connect(function(player)
-- do whatever you need using the part variable
-- from the for loop
end)
end
@CosmicAurz I also want to notify you that this was mostly pseudocode. Obviously you still need to use Instance:GetDescendants() in your for-loop’s parameters, and you should be checking that the part actually is a part with Instance:IsA(“BasePart”) so you’re not creating click detectors where you don’t want them.
1 Like