Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Does Mouse.Changed:Wait() work? It still waits even after moving the mouse.

Asked by
CjayPlyz 643 Moderation Voter
5 years ago
01local Mouse = game:GetService("Players").LocalPlayer:GetMouse()
02local Tool = script.Parent
03local Equipped
04 
05local function Equipped ()
06    Equipped = true
07    local Target = Mouse.Target
08    while Equipped do
09        if Target then
10            print(Target.Name)
11        end
12        Mouse.Changed:Wait()
13    end
14end
15 
16local function Unequipped ()
17    Equipped = false
18end
19 
20Tool.Equipped:Connect(Equipped)
21Tool.Unequipped:Connect(Unequipped)

This will print the name of the mouse.target if mouse.target is not nil and then will wait until the mouse moved. but even if the mouse moved it still doesn’t work. It will only work once and again after re-equipping.

0
I think you can remove the code on line 12 and write this instead; "repeat wait() until Mouse.Changed()" Spjureeedd 385 — 5y
0
no, i have to repeat it everytime it changes. CjayPlyz 643 — 5y
0
and while equipped is set to true CjayPlyz 643 — 5y

1 answer

Log in to vote
2
Answered by 5 years ago
Edited 5 years ago

First, understand how the Wait() method works.

Wait() will yield until an event fires. After that event fires, it stops yielding (it won’t continue to yield after the event fires). So, what it’s doing is that it continues to yield until you move the mouse, then once you do move the mouse, it stops yielding because the event has fired.

Here are a couple of examples:

Example 1

1script.Parent.Touched:Wait()
2wait(2)
3print("Touched")

Example 2

1script.Parent:GetPropertyChangedSignal("Size"):Wait()
2wait(2)
3print(script.Parent.Size)

Both of the above examples will only work once. Wait() stops yielding when the event occurs and the listener stops listening. Such is the behavior of the Wait() method.

However, there are two exceptions:

  • If the listener is within a function and it stops yielding after the event given has occurred, a new listener will be created with every function call.
  • If the listener is within a while loop and the loop stops, the listener also stops. A new listener is created when the loop starts.

The second exception is likely why you are experiencing your situation. Hopefully you understand how it works.

0
oh.. thanks :D CjayPlyz 643 — 5y
Ad

Answer this question