Detect mouse leave from object

  1. What do you want to achieve? Keep it simple and clear!
    So topic could be a bit complicated, exactly i need to turn off selection box when player mouse leaves object
  2. What is the issue? Include screenshots / videos if possible!
    I tryed using while loop, it works but kinda awkward, so i’m asking if there some in-build engine detect of it
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub? I found that piece of code on dev forum, it haves only mouse hover function

Code:

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local UIS = game:GetService("UserInputService")
local ToolName = "WoodPick"

UIS.InputChanged:Connect(function(input, engine_processed)

	if input.UserInputType == Enum.UserInputType.MouseMovement then
		if Mouse.Target:IsA("Part") and Mouse.Target.Name == "HitBox" and Mouse.Target:FindFirstChild("ClickDetector") and Player.Character:FindFirstChild(ToolName) then
			local target = Mouse.Target
			while Mouse.Target:FindFirstChild("ClickDetector") do
				target.SelectionBox.Visible = true
				task.wait(1)
			end
			target.SelectionBox.Visible = false
		end
	end
end)
1 Like

Bumping (no answers bczzzzzzzz)

Something like this should work:

local Object = {
    MouseEnter = Instance.new("BindableEvent"),
    MouseLeave = Instance.new("BindableEvent"),
}

local mouse = game.Players.LocalPlayer:GetMouse()
local old
mouse.Move:Connect(function()
    local new = mouse.Target
    if old ~= new then
        if old then Object.MouseLeave:Fire(old) end
        if new then Object.MouseEnter:Fire(new) end
    end
    old = new
end)

--\\ Connections

Object.MouseEnter:Connect(function(hit)
    print("Point at", hit)
end)

Object.MouseLeave:Connect(function(hit)
    warn("Stop pointing at", hit)
end)

Ah, thank you for a answer, but i already asked ChatGPT 4.0 for solution, and it works perfectly, i will paste a code from it here, if someone need it:

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local UIS = game:GetService("UserInputService")
local ToolName = "WoodPick"
local target

UIS.InputChanged:Connect(function(input, engine_processed)
	if input.UserInputType == Enum.UserInputType.MouseMovement then
		if Mouse.Target and Mouse.Target:IsA("Part") and Mouse.Target.Name == "HitBox" and Mouse.Target:FindFirstChild("ClickDetector") and Player.Character:FindFirstChild(ToolName) then
			target = Mouse.Target
			target.SelectionBox.Visible = true
		end
	end
end)

function unhover()
	target.SelectionBox.Visible = false
end

Mouse.Move:Connect(function()
	if target and (not Mouse.Target or Mouse.Target ~= target) then
		unhover()
		target = nil
	end
end)

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