Player/NPC highlight when mouse is hovering over the character not working properly

Hello, I am working on a script that highlights a player’s character when you’re hovering over it with your mouse. The issue is, sometimes when my mouse is not on a player anymore the highlight remains.

I have no idea how to fix this so any help will be appreciated!

Code:

local Mouse = LocalPlayer:GetMouse()
local HighlightedChar

local function HighlightGive(thing)
	HighlightedChar = thing
	local Highlight = Instance.new("Highlight")
	Highlight.OutlineColor = Color3.fromRGB(24, 205, 255)
	Highlight.FillColor = Color3.fromRGB(42, 163, 255)
	Highlight.Parent = thing
end

local function HighlightRemove()
	if not HighlightedChar then return end
	local Highlight = HighlightedChar:FindFirstChildOfClass("Highlight")
	if Highlight then Highlight:Destroy() end
end

RunService.RenderStepped:Connect(function()
	if not Mouse.Target then return end
	if Mouse.Target.Parent:FindFirstChildOfClass("Humanoid") then
		HighlightGive(Mouse.Target.Parent)
	else
		print("no")
		HighlightRemove()
	end
end)

video

1 Like
if Mouse.Target.Parent:FindFirstChildOfClass("Humanoid") and not Mouse.Target.Parent:FindFirstChildOfClass("Highlight") then --To prevent script to keep adding highlight to the player character 
   HighlightGive(Mouse.Target.Parent)
end

You should add check like

if mouse.Target and not mouse.Target.Parent:FindFirstChild("Humanoid") then
HighlightRemove()
end

And to remove it I used

for _, players in pairs(game:GetService("Players"):GetPlayers()) do
    if  players.Name ~= Mouse.Target.Parent.Name and players.Character:FindFirstChild("Highlight") then
        players.Character.Highlight:Destroy()
    end
end

Also mouse.Target has a disadvantage like when there are 2 players nearby to each other when you hover from one of them to another one it will detect 2 of them as the first player that you hovered your mouse on.

1 Like