MouseEnter and MouseLeave not working correctly

So I have been trying to create buttons that will tween their size outwards when you hover your mouse over them. I have been trying to use MouseEnter() and MouseLeave() to do this, but when I move my mouse quickly, it doesn’t detect mouseleave, and the buttons stay the same size instead of shrinking back to normal.

Here is the code for a button:

local Button = script.Parent

Button.MouseEnter:Connect(function()
	Button:TweenSize(UDim2.new(0,250,0,63), Enum.EasingDirection.InOut, Enum.EasingStyle.Linear, 0.1)
	script.Sound:Play()
end)

Button.MouseLeave:Connect(function()
	Button:TweenSize(UDim2.new(0,210,0,63), Enum.EasingDirection.InOut, Enum.EasingStyle.Linear, 0.1)
end)

Is there a more reliable method than MouseEnter() and MouseLeave() to accomplish this? Or is it a problem with TweenSize(), and should I use TweenService instead?

I have a feeling this is an easy fix, but I am having some trouble with it. Any help is appreciated.

4 Likes

There are a few things to consider here:

  1. The old tween methods have an override parameter that allows an in-progress tween to be overridden by another tween on the same object. I believe that is the core issue here.

  2. These methods are deprecated, so you should prefer TweenService, which overrides tweens by default.

  3. MouseEnter and MouseLeave have been historically unreliable. I have a simple workaround described here.

2 Likes

I gave up on MouseLeave long ago. Try just MouseEnter then hover checks for leaving.

Alternatively, one can use the recently added GuiState property like so:

local TweenService = game:GetService("TweenService")

local TWEEN_INFO = TweenInfo.new(0.1, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut)

local Button = script.Parent

local tween = TweenService:Create(Button, TWEEN_INFO, {})

Button:GetPropertyChangedSignal("GuiState"):Connect(function()
	if Button.GuiState == Enum.GuiState.Hover then
		tween:Cancel()
		tween = TweenService:Create(Button, TWEEN_INFO, {Size = UDim2.new(0, 250, 0, 63)})
		tween:Play()

		script.Sound:Play()
	elseif Button.GuiState == Enum.GuiState.Idle then
		tween:Cancel()
		tween = TweenService:Create(Button, TWEEN_INFO, {Size = UDim2.new(0, 210, 0, 63)})
		tween:Play()
	end
end)

Your suggestions are correct, though :slight_smile::+1:

@Carl_Weezer13

5 Likes

This looks pretty sweet and I agree, MouseLeave needs a workaround.

1 Like

I don’t think this comes down to being unreliable. This is more of a keeping the calls generic. It would be easy enough for Roblox to create commands for this that are rock solid but, that would take away from processor time and resources. Same goes for touch. They are made purposely to be generic and optimized. So they do seem to act a bit odd. Unless you consider this point.

Thank you all for your replies, I will work on this ASAP.

1 Like

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