Purchases Firing Multiple Times: how do I disconnect it?

I have a purchase script which allows players to purchase items, however, there’s an issue. The connection of clicking on the buyButton does not disconnect when the player clicks noButton. I’ve tried to fix it myself multiple times but just can’t seem to find a way around it. The function I’m using is below;

local function buyItem()
	clickSound:Play()
	script.Parent.Parent.Parent.Visible = false

	local confirmationUI = player.PlayerGui["User Interface"].UserUI.SwordConfirmationUI
	confirmationUI.SwordName.Text = script.Parent.Name

	if confirmationUI then
		confirmationUI.Visible = true
		confirmationUI.GemsCost.Text = gemCost
		confirmationUI.SwordImage.Image = script.Parent.ImageLabel.Image
		local yesButton = confirmationUI:FindFirstChild("YesButton")
		if yesButton then
			yesButton.MouseButton1Click:Connect(function()
				local checkGems = game.ReplicatedStorage.Functions.CheckGems:InvokeServer(gemCost)
				if checkGems == true then
					swordPurchasedEvent:FireServer(sword)
					confirmationUI.Visible = false
					equipButton.Visible = true
					TweenUI()
					game.ReplicatedStorage.GameSounds.PurchaseSound:Play()
				else
					print("Not enough gems")
				end
			end)
		end

		local noButton = confirmationUI:FindFirstChild("NoButton")
		if noButton then
			noButton.MouseButton1Click:Connect(function()
				confirmationUI.Visible = false
				clickSound:Play()
				script.Parent.Parent.Parent.Visible = true
			end)
		end
	end
end

If anyone could offer any advice or tips on how I would disconnect the yesButton connection when the noButton (nevermind) is pressed I would appreciate it, thanks! :happy3:

Visual Representation of the issue:

1 Like

RBXScriptSignal:Connect returns an RBXScriptConnection. I think the quickest and easiest solution would be to save a reference to the connection that gets returned from yesButton.MouseButton1Click:Connect(...) in a variable, and in the callback for noButton, disconnect the connection there.

Personally though, I wouldn’t repeatedly create connections every time the confirmation UI pops up since that seems unnecessary. I’d have some initializing code for all the UI that sets up all the button callbacks just once so you don’t need to worry about this type of thing happening.

2 Likes