Problems with text fading in (mouse hover)

So, what I’m basically trying to do is fading text in once a player hovers over a brick. And it works alright but there’s an issue: if you hover over the brick, move your mouse (the mouse is still on the brick) then the fading animation will start again. How would I fix it?
I’m not that experienced with Roblox Lua so uh sorry if the answer is really obvious.

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local label = script.Parent

function updatePos()
	local target = mouse.Target
	if target and target:FindFirstChild("MouseoverText") then
		label.Position = UDim2.fromOffset(mouse.X, mouse.Y)
		label.Text = target.MouseoverText.Value
		label.Visible = true
		for i = 1, 0, -.05 do
			label.TextTransparency = i
			wait(.05)
		end
	else
		label.Visible = false
	end
end

mouse.Move:Connect(updatePos)

updatePos()

I believe you’re going to have to store the previous target from the last call and then check that with the if statement. Just while I’m describing it, I’ll name it prevTarget. Lets say the player moves their mouse. Currently, it’s on the baseplate for 2 frames and as such prevTarget on frame2 is Baseplate.

Now, lets say the player moves their mouse onto the proper target, i.e. MouseoverText, since prevTarget was baseplate they wont be the same, so it’ll be updated to the MouseoverText and just run the code. Now, if the player moves the mouse while it’s on the brick nothing will happen as expected, until they move it off target to baseplate where prevTarget becomes that.

A simpler fix would be to add a debounce.

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local label = script.Parent
local debounce = false

function updatePos()
	local target = mouse.Target
	if target and target:FindFirstChild("MouseoverText") then
        if debounce == false then
           debounce = true
           label.Position = UDim2.fromOffset(mouse.X, mouse.Y)
	       label.Text = target.MouseoverText.Value
	       label.Visible = true
	       for i = 1, 0, -.05 do
               label.TextTransparency = i
	 	       wait(.05)
	       end
       end
	else
        debounce = false
		label.Visible = false
	end
end

mouse.Move:Connect(updatePos)

updatePos()


Something like that.

1 Like