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

How do you deactivate this when you're not clicking?

So I am making a tool that puts a meatloaf where you click however when you stop clicking the function still continues please help!

Code:

local tool = script.Parent
local IsE = 0
local IsC = 0
local mouse = game.Players.LocalPlayer:GetMouse()
local laser = game.ServerStorage.Laser

function onClicked(mouse)
	
	local mouse = game.Players.LocalPlayer:GetMouse()
      tool.Fire1.BrickColor=BrickColor.Red()
  	  laser.Parent=workspace
		while true do
		game.Workspace.MeatLoaf.Position=mouse.Hit.p
		wait(0.1)
		end
end
function Equipped(mouse)
mouse.Button1Down:connect(onClicked)
end
tool.Equipped:connect(Equipped)
function offClicked(mouse)
      tool.Fire1.BrickColor=BrickColor.Black()
end
mouse.Button1Up:connect(offClicked)

1 comment

0

You use a while true do, this can only be canceled by inserting a break.

1 answer

✓ Accepted answer

First off, your code is a mess lol. I highly recommend using anonymous functions so that you can nest events inside each other. It will look a lot nicer and be more organized:

tool.Equipped:connect(function(mouse)

	mouse.Button1Down:connect(function()
		--click
	end)

	mouse.Button1Up:connect(function()
		--unclick
	end)

end)

Anyways, the reason your code never stops is that you never tell it to stop. On line 12, you start an infinite loop. It's gonna keep running no matter what.

I'll show you a pretty easy method in order to get around this. Create a variable. When a player clicks, make it true. When a player unclicks, make it false. Then create an infinite loop outside the events, checking what the variable equals and running code based on that.

local clicked = false

tool.Equipped:connect(function(mouse)

	mouse.Button1Down:connect(function()
		clicked = true
	end)

	mouse.Button1Up:connect(function()
		clicked = false
	end)

end)

while wait(0.1) do
	if clicked then
		--code
	end
end

1 comment

0

Could you also use API:Class/UserInputService/InputEnded? Since hes no longer interacting with the mouse, can you connect this event to the function?

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