How to destroy "SelectionBox", created by instance.new()?

  1. What do you want to achieve? Keep it simple and clear!
    Destroy SelectionBox when mouse leave from part.
  2. What is the issue? Include screenshots / videos if possible!
    I tryed get an child, but can’t.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

mouse.Move:Connect(function()
	local target = mouse.Target
	
	if target then
		print(target.Name)
		local box = Instance.new("SelectionBox")
		box.Parent = target
		box.Adornee = target
	end
	
	if not target then
		for i,v in pairs(target:GetChildren()) do
			if v.ClassName == "SelectionBox" then
				v:Destroy()
			end
		end
	end
end)

Hi,
do you try it with mouseEnter:connect and MouseLeave:Connect function?

I believe these are reserved for GUIs.

@Tysmaii Basically, you need to store the target that you’re currently mousing over. You then destroy the selection boxes in it if the mouses current target is no longer the old target.

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local currentTarget = nil

mouse.Move:Connect(function()
	local target = mouse.Target
	
	if target ~= nil and target ~= currentTarget then
		print(target.Name)
		local box = Instance.new("SelectionBox")
		box.Parent = target
		box.Adornee = target
		for i,v in pairs(currentTarget:GetChildren()) do
			if v:IsA("SelectionBox") then
				v:Destroy()
			end
		end
		currentTarget = target
	elseif target == nil then
		if currentTarget then
			for i,v in pairs(currentTarget:GetChildren()) do
			if v:IsA("SelectionBox") then
				v:Destroy()
			end
		
			currentTarget = nil
			end
		end
	end
	
	
		
	
end)

Hi,
I think this is good idea, but no, not try.

Thanks for your reply! I will note his decision. But still, I’ll answer, I’ve found an easier way.

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

local debounce = false

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

	if target and target ~= workspace.Baseplate then
		print(target.Name)
		game.Workspace.SelectionBox.Adornee = target
	else
		game.Workspace.SelectionBox.Adornee = nil
	end
end)