Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

local Mouse = game:GetService("Players").LocalPlayer:GetMouse()
local Tool = script.Parent
local Equipped

local function Equipped ()
	Equipped = true
	local Target = Mouse.Target
	while Equipped do
		if Target then
			print(Target.Name)
		end
		Mouse.Changed:Wait()
	end
end

local function Unequipped ()
	Equipped = false
end

Tool.Equipped:Connect(Equipped)
Tool.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.

3 comments

0

I think you can remove the code on line 12 and write this instead; "repeat wait() until Mouse.Changed()"

0

no, i have to repeat it everytime it changes.

0

and while equipped is set to true

1 answer

✓ Accepted answer

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

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

Example 2

script.Parent:GetPropertyChangedSignal("Size"):Wait()
wait(2)
print(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.

1 comment

0

oh.. thanks :D

This discussion is preserved as it was. New answers, comments, and votes are closed.