Check various click detectors created with Instance.new

Hello! The idea I have for the script is to create a Selection Box and a Click Detector in the head of each player in the match, and then detect if the player presses one of the Detectors.

for i,v in pairs(game.Players:GetPlayers()) do
	if v ~= game.Players.LocalPlayer then
			local box = Instance.new("SelectionBox")
			local click = Instance.new("ClickDetector")
			box.Color3 = Color3.fromRGB(255, 0, 0)
			box.Parent = v.Character.Head
			click.Parent = v.Character.Head
        --Then the script would somehow check if the player has pressed one of 
        ---the Detectors and also retrieve which one
	end
end

I know this would require the :MouseClick event, but I don’t how I could do this with multiple Click Detectors

2 Likes

Since you are using a for loop it should be possible to connect it to each of them.

Do it the same way you would do it to work for one player, the for loop will extend it to all players. Keep in mind that the code within the for-loop only knows of the things within that current for loop.

This means that if you had player1, player2 and player3 the loop would only fire the code connected to the respective players clickdetector. For example:

If player1 is clicked, then only player1’s clickdetector will know it was clicked.

1 Like

For each click detector, you connect the ‘MouseClick’ event to a function. Once we do that, we can just pass in those parameters to that event.

If you have any questions, please let me know!

local function onClicked(clickDetector: ClickDetector, fromPlayer: Player)
	-- do stuff
end

for _, player in pairs(game.Players:GetPlayers()) do
	if player ~= game.Players.LocalPlayer then
		local box = Instance.new("SelectionBox")
		local click = Instance.new("ClickDetector")
		box.Color3 = Color3.fromRGB(255, 0, 0)
		box.Parent = player.Character.Head
		click.Parent = player.Character.Head

		click.MouseClick:Connect(function(plr: Player)
			onClicked(click, plr)
		end)
	end
end
local folder = workspace.Folder --Example folder of ClickDetector instances.

local function onClicked(clickDetector, player)
	--'clickDetector' is a reference to the ClickDetector instance that was clicked.
	--'player' is a reference to the player instance that clicked the ClickDetector instance.
end

for _, clickDetector in ipairs(folder:GetChildren()) do --Replace with "GetDescendants()" if necessary.
	if clickDetector:IsA("ClickDetector") then
		clickDetector.MouseClick:Connect(function(player)
			onClicked(clickDetector, player)
		end)
	end
end
1 Like

Is this in a localscript, if so change it to server-based to prevent exploits. And the above solutions would help u out, so I dont see the need to post my own solution.

1 Like