Using ClickDetector 'MouseHoverLeave' in a model has undesired effects

A case of the script working fine then all of a sudden not working.
I made a script to attempt to highlight the object the player’s looking at (with SelectionBox), which works fine the first 2 times on hovering it and then the opposite happens.
Arrangement:
image
Script:

local c = script.Parent.ClickDetector
local d = script.Parent

c.MouseHoverEnter:Connect(function()
	for _,Part in pairs(d:GetDescendants()) do
		if Part:IsA("BasePart") then
			local b = Instance.new("SelectionBox")
			b.LineThickness = 0.025
			b.Color3 = Color3.fromRGB(255,255,0)
			b.SurfaceColor3 = Color3.fromRGB(255,255,0)
			b.SurfaceTransparency = 1
			b.Transparency = 0.5
			b.Parent = Part
			b.Adornee = Part
			wait()
		end
		c.MouseHoverLeave:Connect(function()
			wait()
			Part:WaitForChild("SelectionBox", math.huge):Destroy()
		end)
	end
end)

Video:


I think I know that the issue is when it leaves one Part and goes to another it sees it as leaving the whole model, probably. I’m looking for a way to fix this not a work-around like a invisible part or something. Thanks in advance.

1 Like

Try to put

c.MouseHoverLeave:Connect(function()
	wait()
 	Part:WaitForChild("SelectionBox", math.huge):Destroy()
end)

outside of

c.MouseHoverEnter:Connect(function()
	for _,Part in pairs(d:GetDescendants()) do
		if Part:IsA("BasePart") then
			local b = Instance.new("SelectionBox")
			b.LineThickness = 0.025
			b.Color3 = Color3.fromRGB(255,255,0)
			b.SurfaceColor3 = Color3.fromRGB(255,255,0)
			b.SurfaceTransparency = 1
			b.Transparency = 0.5
			b.Parent = Part
			b.Adornee = Part
			wait()
		end
		c.MouseHoverLeave:Connect(function()
			wait()
			Part:WaitForChild("SelectionBox", math.huge):Destroy()
		end)
	end
end)
2 Likes

thank you this works, i just also had to add a pairs loop again. :+1:

2 Likes

No problem, I’m really glad that it helped! :+1:

2 Likes