Easier way to check for hovering over objects

Just a quick question, I was looking to create a dialogue tree system, but I realized that if I wanted to highlight the NPC the player’s mouse is hovering over, I would need to use while true do loops. This is very resource intensive. Are there any bypasses or special ‘:hover()’ functions that I might be missing?

This was just a rough draft of what I was trying to do.

-- [Variables]
local Player = game:GetService('Players').LocalPlayer
local HighlightedPlayer, CurrentlyHighlighting = nil, false
local Highlight = Instance.new('Highlight')

-- [Script]
while game:GetService('RunService').Heartbeat:Wait() do
	if not Player:GetMouse() then return end
	
	if Player:GetMouse().Target then
		local Part =  Player:GetMouse().Target
		
		if Part.Name == 'DialogueHitbox' then
			Highlight.Parent = Part.Parent.Parent
		else
			Highlight.Parent = nil
			CurrentlyHighlighting = true
		end
	else
		Highlight.Parent = nil
		CurrentlyHighlighting = true
	end
end

This is a video of what I’m trying to do.

I could optimize the script with only doing it when the mouse moves but that’s only a rough draft

You should just be using a RenderStepped connection.

You could look at throwing a ClickDetector on the model. The cursor should change and that object has hover events you can put listeners on. Can also set an activation distance.

Loops are far from resource intensive. In fact, the events you wish to use are built on top of engine loops

1 Like

Ahh noo you may use this instead way better than clickdetectors:

local UserInputService = game:GetService("UserInputService")
local lastTarget = nil

UserInputService.InputChanged:Connect(function(input)
	if not mouse then return end

	if mouse.Target and mouse.Target:FindFirstChild("Highlight") then
		if lastTarget ~= mouse.Target then
			if lastTarget and lastTarget:FindFirstChild("Highlight") then
				lastTarget.Highlight.Enabled = false
			end
			mouse.Target.Highlight.Enabled = true
			lastTarget = mouse.Target
		end
	elseif lastTarget and lastTarget:FindFirstChild("Highlight") then
		lastTarget.Highlight.Enabled = false
		lastTarget = nil
	end
end)

I just copy pasted the script I used in my games it basically checks the movement of the mouse

1 Like

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