Hello, I've been developing a script that when the mouse left button is held down, a value is incremented until the left button is released. My goal is that while the mouse is down and simultaneously if the object that the mouse is hovering over changes, the value would be reset to zero, and would still increment. The following is my code/ attempt:
local Player= game.Players.LocalPlayer local Mouse= Player:GetMouse() local holdSwitch= 0 local holdVal= 0 --compares difference between object 1 and 2 local obj1= Mouse.Target.Position local obj2= Mouse.Target.Position local screenGUI= Instance.new("ScreenGui",game.Players.LocalPlayer.PlayerGui) screenGUI.Name= "screenGUI" --GUI for holding down mouse key local textLabelHoldMouse= Instance.new("TextLabel",screenGUI) textLabelHoldMouse.Name= "HoldMouse" textLabelHoldMouse.Position= UDim2.new(0,10,0,400) textLabelHoldMouse.Size= UDim2.new(0,150,0,25) textLabelHoldMouse.BorderSizePixel= 0 textLabelHoldMouse.BackgroundTransparency= 1 textLabelHoldMouse.TextColor3= BrickColor.White().Color textLabelHoldMouse.Text= "Hold: " textLabelHoldMouse.TextXAlignment= "Left" textLabelHoldMouse.TextTransparency= 0--toggle --detection script local vb= 0 Mouse.Button1Down:connect(function() --with distance if; numMode indicates build or destroy if workspace.numMode.Value== 0 and tostring(Mouse.Target)== "DirtBlockClone" and Player:DistanceFromCharacter(Mouse.Target.Position)< 16 then Mouse.Button1Up:connect(function()--stops count and resets holdVal holdSwitch= 1 holdVal= 0 --textLabelHoldMouse.Text= "Hold: "..holdVal end) holdSwitch= 0 while holdSwitch== 0 do wait(0) holdVal= holdVal+1 textLabelHoldMouse.Text= "Hold: "..holdVal if not obj1== obj2 then holdVal= 0 end end end end)
So, I instantiate a comparison for each step of the wait interval, and it would test if the object target position has changed. I'm not sure what is going wrong.
Add a variable target
equal to Mouse.Target
and check in the while loop to see if Mouse.Target
does not match target
. If it doesn't, update target
and set holdVal=0
.
Just a warning: Calling Mouse.Button1Up:connect
every time you click creates a new connection every time you click, and since it isn't just a callback, it isn't just overwritten. The connection should be made only once.