Highlighting objects when cursor hovers over object

I’m having a hard time trying to make a system where you simply add a highlight, then delete the highlight when the mouse is no longer hovering over the object. My system currently is slow, and sometimes, the highlight will be flashing randomly.(specifically when having your cursor on models) Is there better ways to go about this besides the mouse.target method?

(help for understanding code: if the model has the bool canTp then it adds a highlight. If the cursor is no longer on the highlight, delete the lasthit’s highlight )

local character = script.Parent
local player = game.Players.LocalPlayer
local UIS = game:GetService("UserInputService")
local Debris = game:GetService("Debris")
local mouse = player:GetMouse()  
local maxDis = script:WaitForChild("MaxDis").Value
local lastHit = nil

UIS.InputChanged:Connect(function(input)
	
	local hit = mouse.Target
	
	if hit then
		
		if hit:FindFirstChild("CanTp") or hit:FindFirstAncestorWhichIsA("Model"):FindFirstChild("CanTp") then

			if hit:FindFirstAncestorWhichIsA("Model") and hit:FindFirstAncestorWhichIsA("Model"):FindFirstChild("CanTp") ~= nil then
				lastHit = hit.Parent
				if hit.Parent:FindFirstChildWhichIsA("Highlight") == nil then
					local highlight = Instance.new("Highlight")
					highlight.FillColor = Color3.fromRGB(255, 255, 255)
					highlight.Parent = hit.Parent
				end
				
			else  
				lastHit = hit
				if hit:FindFirstChildWhichIsA("Highlight") == nil then
					
					local highlight = Instance.new("Highlight")
					highlight.FillColor = Color3.fromRGB(255, 255, 255)
					highlight.Parent = hit
				end
			
			end
		end
		
		if lastHit ~= hit then
			Debris:AddItem(lastHit.Highlight, 0.1)
			lastHit = nil
		end
		
	end
end)
2 Likes

edit: figured it out
(with a tutorial lol)
‘’
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local mouse = player:GetMouse()

local CollectionService = game:GetService(“CollectionService”)

local maximumDistance = 45

mouse.Move:Connect(function()

if not mouse.Target then 
	script.Highlight.Adornee = nil  return 
end

if (mouse.Target.Position - character.HumanoidRootPart.Position).Magnitude > maximumDistance then 
	script.Highlight.Adornee = nil return 
end

if CollectionService:HasTag(mouse.Target, "Hightlightable") then
	script.Highlight.Adornee = mouse.Target
	return
		
elseif CollectionService:HasTag(mouse.target.Parent, "Hightlightable") then
	script.Highlight.Adornee = mouse.Target.Parent
	return
		
end

script.Highlight.Adornee = nil

end)
‘’

3 Likes

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