Userinputservice firing in a paused coroutine

hi, when i pause my coroutine, the print stops running as intended, but the left click is still firing for some reason. i’m trying to make it so you can only left click when the coroutine is running

local uis = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local buildingGui = player.PlayerGui:WaitForChild("BuildingGui")
local stopBuildMode = false

local buildMode = coroutine.create(function()
	while task.wait() do
		
		-- cancel
		if stopBuildMode == true then
			coroutine.yield()
		end
		
		print("aaaa")
		
		uis.InputBegan:Connect(function(input)
			if input.UserInputType == Enum.UserInputType.MouseButton1 then
				print("click")
			end
		end)
			
	end
end)

-- enter build mode
for _, button in buildingGui.Frame:GetChildren() do
	if button:IsA("TextButton") then
		button.MouseButton1Click:Connect(function()
			
			stopBuildMode = false
			coroutine.resume(buildMode)
			buildingGui.Frame.Cancel.Visible = true
		end)
	end
end

-- cancel
uis.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.Q and buildingGui.Frame.Cancel.Visible == true then
		
		buildingGui.Frame.Cancel.Visible = false
		stopBuildMode = true
		
	end
end)

1 Like

Every time you invoke InputBegan:Connect() you are creating a new RBXScriptConnection which will persist until you disconnect it. Every cycle of your loop, you are creating a new connection which is around 60 connections per second. So when the user triggers MouseButton1, “click” will be printed for however many connections you have made (thousands). What you should be doing is checking for MouseButton1 inside the main connection, that way every time the MouseButton1 event is fired you only print click once after checking if the user is in build mode. I’m not sure why ChatGPT told you to use coroutines, but this should work.

local UserInputService = game:GetService("UserInputService")
local player = game.Players.LocalPlayer

local buildingGui = player.PlayerGui:WaitForChild("BuildingGui")
local buildingModeActive = false

-- Enter Build Mode
for _, button in buildingGui.Frame:GetChildren() do
	if button:IsA("TextButton") then
		button.MouseButton1Click:Connect(function()
			buildingModeActive = true
			buildingGui.Frame.Cancel.Visible = buildingModeActive
		end)
	end
end

-- Handle User Input
UserInputService.InputBegan:Connect(function(input)
	if buildingModeActive then
		if input.KeyCode == Enum.KeyCode.Q then
			buildingModeActive = false
			buildingGui.Frame.Cancel.Visible = buildingModeActive
		elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
			print("click")
		end
	end
end)
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.