Problems with Mouse.Target

Hi, I’m trying to create a script where an outline appears around a specific part when hovering over it. But when I try to implement it works fine but it spews out error messages as soon as the mouse stops hovering over a part.

This is what the part looks like in the explorer:
explorer

this is the output window whenever I hover the mouse over a void:

and this is the entire script:

local run = game:GetService("RunService")
local player = script.Parent.Parent

local mouse = player:GetMouse()

run.RenderStepped:Connect(function()
	
	if mouse.Target:FindFirstChild("interact") then
		mouse.Target.interact.Enabled = true
	else
		return false
	end
	
end)

You need to check if there is a Target, because if the target is null then you can’t call the FindFirstChild method; it’s like you are doing this: nill:FindFirstChild(). You need to check if there is a target first.

if not mouse.Target then return end
1 Like

Here is my script, I wouldn’t use the run server in this case:


local UIS = game:GetService("UserInputService")

local player = game.Players.LocalPlayer

local mouse = player:GetMouse()



UIS.InputChanged:Connect(function(input)

	if mouse.Target then
		local part = game.Workspace.Part
		if mouse.Target == part then

			Instance.new("Highlight", part)



		else

			if part:FindFirstChild("Highlight") then
				part.Highlight:Destroy()
			end

		end

	end

end

I got lazy and made it so that the highlight was added, not cloned. But just like what @MakerDoe said.

try this


local run = game:GetService("RunService")
local player = script.Parent.Parent

local mouse = player:GetMouse()

run.RenderStepped:Connect(function()
	if not mouse.Target then
else
	if mouse.Target:FindFirstChild("interact") then
		mouse.Target.interact.Enabled = true
	else
		return false
	end
	end
end)

This isn’t really necessary; what you are doing is just adding more conditions when you can simply end when it finds nothing.

oh, that makes sense. Great explanation!

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