UIS.InputBegan fires multiple times

This is my code (don’t worry about the first part with the ghost and all that), the placeEvent bindableEvent (check last line) is being fired from another localscript when i click a button. The problem is that the function connected to UIS.InputBegan fires multiple times. I know this bc i printed “place part” if i press left click. Each time the function fire 1 more time. The first time it fires once like it’s supposed to. The second time it fires 2 times for 1 left click. Third time 3 fires and so on. I know this is just something wrong with my script but idk what it is. Could someone please explain?

local RunService = game:GetService("RunService")
local UIS = game:GetService("UserInputService")
local placeEventServer = game.ReplicatedStorage:WaitForChild("PlaceEvent")

function place(localItem)
	local part = localItem:WaitForChild("Part").Value:WaitForChild("model").value
	local ghost = part:Clone()
	ghost.Anchored = true
	ghost.CanCollide = false
	ghost.CanQuery = false	
	ghost.Transparency = .5
	ghost.Color = Color3.new(0, 1, 0)
	ghost.Parent = game.Workspace
	
	local bind = RunService.RenderStepped:Connect(function()
		ghost.Position = game.Players.LocalPlayer:GetMouse().Hit.Position + Vector3.new(0,ghost.Size.Y/2,0)
	end)
	UIS.InputBegan:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.MouseButton2 then
			bind:Disconnect()
			ghost:Destroy()
			return
		elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
			print("place part")
			placeEventServer:FireServer(part)
		end
	end)
end



script.Parent:WaitForChild("placeEvent").Event:Connect(place)	

Each time the function place is called a connection is made to UserInput’s InputBegan RBXScriptSignal object.

You need to either disconnect this connection on each subsequent call to the function or prevent the connection from being recreated.

local RunService = game:GetService("RunService")
local UIS = game:GetService("UserInputService")
local placeEventServer = game.ReplicatedStorage:WaitForChild("PlaceEvent")

local connection

function place(localItem)
	local part = localItem:WaitForChild("Part").Value:WaitForChild("model").value
	local ghost = part:Clone()
	ghost.Anchored = true
	ghost.CanCollide = false
	ghost.CanQuery = false	
	ghost.Transparency = .5
	ghost.Color = Color3.new(0, 1, 0)
	ghost.Parent = game.Workspace

	local bind = RunService.RenderStepped:Connect(function()
		ghost.Position = game.Players.LocalPlayer:GetMouse().Hit.Position + Vector3.new(0,ghost.Size.Y/2,0)
	end)
	
	if connection then return end
	connection = UIS.InputBegan:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.MouseButton2 then
			bind:Disconnect()
			ghost:Destroy()
			return
		elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
			print("place part")
			placeEventServer:FireServer(part)
		end
	end)
end
2 Likes