Is there a way to up date MouseHoverEnter without Heartbeat()

My script works, but I feel like it’s not the most optimized, but basically I want a gui to showup whenever someone hovers over an object, but which object shows the gui changes every once in awhile. Basically I used a string value to get this, and then let mousehoverenter use that string value to find out if that object was the one it was going to show. I’m sorry if that sounds confusing, but my issue might clear it up.

Basically my issue is that it shows up when the game starts and the stringvalue updates, but any time after that it doesn’t show. I decided to add RunService.Heartbeat to it, and this works, but I’m not sure if that’s the most optimized

function SelectBrick()
	OptionBrick = workspace.Options:WaitForChild(selected.Value).ClickDetector
	print(selected.Value.. "works")
end
wait(1)
SelectBrick()

selected.Changed:Connect(function()
		SelectBrick()
		print("This is "..OptionBrick.Parent.Name)
end)

RunService.Heartbeat:Connect(function()
	workspace.Options[selected.Value].ClickDetector.MouseHoverEnter:Connect(function()
		if OptionBrick.Parent.Name == "OptionOneOneBrick" then
			HoverOptionOneOne.Visible = true
		elseif OptionBrick.Parent.Name == "OptionOneTwoBrick" then
			HoverOptionOneTwo.Visible = true
		elseif OptionBrick.Parent.Name == "OptionOneThreeBrick" then
		HoverOptionOneThree.Visible = true
	end
end)

workspace.Options[selected.Value].ClickDetector.MouseHoverLeave:Connect(function()
	if OptionBrick.Parent.Name == "OptionOneOneBrick" then
		HoverOptionOneOne.Visible = false
	elseif OptionBrick.Parent.Name == "OptionOneTwoBrick" then
		HoverOptionOneTwo.Visible = false
	elseif OptionBrick.Parent.Name == "OptionOneThreeBrick" then
		HoverOptionOneThree.Visible = false
	end	
end)	
end)

The script is a lot longer, but that’s the part that I think is important. Tell me if there’s anymore I need to show. Thanks!

1 Like

On top of being unoptimised, I am pretty sure you’re leaking memory too, because now every frame you’re creating a new connection on the ClickDetector. You’ve got two options: swap the order of connections (Heartbeat in the ClickDetector) provided you disconnect the Heartbeat connection when the mouse is no longer hovered, or divorce updating the hover option from the ClickDetector function.

1 Like

A better way to do this is to use the PlayerMouse. You can get the player’s mouse on the client by using :GetMouse() method on LocalPlayer (game:GetService("Players").LocalPlayer:GetMouse()). From that, you can use Mouse.Target to get the part the mouse is hovering over. Use Mouse.Moved in lieu of heartbeat.

Source: PlayerMouse | Documentation - Roblox Creator Hub

1 Like

Hey, thanks I had totally forgotten about this even though I had just used it a week ago somehow. So thanks for reminding me of it, and it helped me make my code ten times cleaner as well.