Part repeatedly cloning when hovering / How to make part only clone once?

I have a script that inserts a cloned ClickDetector over the part I’m hovering over. It should insert it once, and destroy that clone if my mouse isn’t on the part anymore.

However, when I hover the mouse over the part, every time the mouse moves, the ClickDetector gets inserted tons of times.

How can I make it so that it only clones once?

my script for reference

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local values = plr.PlayerGui.Input.TextBox
local click = Instance.new("ClickDetector")
local c

mouse.Move:Connect(function()
	local target = mouse.Target

	for _,blocks in pairs(workspace.Blocks:GetChildren()) do
		if target == blocks then
			
			c = click:Clone()
			c.Parent = target
			values.id.TextTransparency = 0
			values.PartName.Text = target.Name
		else
			c:Destroy()
			values.id.TextTransparency = 1
			values.PartName.Text = ""
		end
	end
end)

Use an if statement to check if target:FindFirstChildWhichIsA(“ClickDetector”) equals false.

1 Like
local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local values = plr.PlayerGui.Input.TextBox
local click = Instance.new("ClickDetector")
local c

mouse.Move:Connect(function()
	local target = mouse.Target

	for _,blocks in pairs(workspace.Blocks:GetChildren()) do
		if target == blocks then

			if not(blocks:FindFirstChild("ClickDetector")) then
				c = click:Clone()
				c.Parent = target
				values.id.TextTransparency = 0
				values.PartName.Text = target.Name
			end

		else
			if blocks:FindFirstChild("ClickDetector") then
				c:Destroy()
				values.id.TextTransparency = 1
				values.PartName.Text = ""
			end
		end
	end
end)

Haven’t tested but this should work.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.