How do I make multiple Clickdetectors work in one script?

I have many objects in a Folder in workspace with a clickdetector, Instead of adding a script in every clickdetector, i want to do it in a module script somehow, could anyone assist me on how to do that? I don’t know how to detect the clicking…

3 Likes

Just write whatever your code is on the module.

local module = {}

function onClick()
    print("Hello World!")
end)

return module

And whenever one of the clickdetectors is cliked do:

local module = require(game.ReplicatedStorage.Module)

script.Parent.MouseClick:Connect(function()
    module.onClick()
end)

Is that it or did i miss something?

I think you want something like this:

local function onClick(player)
    print(player.Name.." clicked me")
end

local folderWithTheObjs = game.Workspace.Folder

for _, child in pairs(folderWithTheObjs) do
    if not child:IsA("ClickDetector") then return end
    child.MouseClick:Connect(onClick)
end
3 Likes

Where would I put that? I don’t see anything with a Module :smiley: Is that a serverside script? Also, will it update when a new object gets added into the folder? If no, how would i do that?

https://developer.roblox.com/en-us/api-reference/class/CollectionService

Hey OP, use CollectionService and the Tag Editor plugin. CollectionService provides the ability to tag instances with arbitrary strings, and allows you to call :GetTagged(string) to get a table of every instance that has been tagged with that string. Tag Editor provides an easy-to-use method for tagging parts while in Studio.

There’s no need to use ModuleScripts for this either, if you don’t want to.

  1. Use Tag Editor to tag all ClickDetectors with one tag. (We’ll use “Foobar”)
  2. In a script, call CollectionService:GetTagged(“Foobar”) to get an array of instances tagged as “Foobar”
  3. Loop through the array, connecting ClickDetector.MouseClick to your desired function.

Example code:

local CollectionService = game:GetService("CollectionService")

for _, tagged in CollectionService:GetTagged("Foobar") do
  tagged.MouseClick:Connect(function() print("Hello, world!") end)
end
4 Likes