How would I go about making a script that fires any time a clickdetector is used? I have a ton of clickdetectors in my game and I don’t want to make events for all of them.
Like @Dullcimer said, CollectionService
could be your way to go here. Here’s a quick rundown of how you could implement this.
- Run a command in your studio command bar to add a certain tag to all your
ClickDetector
instances:
for i, v in next, game:GetDescendants(), nil do if not v:IsA("ClickDetector") then continue end v:AddTag("Clickable") end
- You will still need to make a connection for each
ClickDetector
, but you can now control it all with one script.
local cs = game:GetService("CollectionService")
for _, detector in next, cs:GetTagged("Clickable"), nil do
detector.MouseClick:Connect(print) --should output which player clicked the detector
end
Alternate method:
Just run an iteration on the game’s descendants and do the same thing.
for _, v in next, game:GetDescendants(), nil do
if not v:IsA("ClickDetector") then continue end
v.MouseClick:Connect(print)
end
for either method, you will still need to make a connection for each click detector. This will likely be the case no matter what method you use.
(unless you use a rubbish method like raycasting and child finding)
You might want to consider casting a ray when the player clicks (using Mouse.Hit, or casting the ray yourself, you can even ignore transparent parts this way), and if the target part has a click detector, then you can fire code. At that point, if you don’t use the Click Detector for anything else, you could strait up remove it and instead tag the clickable parts, and check that tag when the player clicks