I need a function to stop after something happens

I know, this looks pretty nooby, but I’m working on a giving system that includes a confirmation UI. The code looks like this:

local prompt = script.Parent

prompt.Triggered:Connect(function(player)
	print("pluh")
	local otherPlayer = game.Players:GetPlayerFromCharacter(character)
	local tool = player.Character:FindFirstChildWhichIsA("Tool")
	if tool then
		game.ReplicatedStorage.GiveRequest:FireClient(otherPlayer, player, tool)
		otherPlayer.PlayerGui.MainGui.GiveFrame.Visible = true
		otherPlayer.PlayerGui.MainGui.GiveFrame.Accept.MouseButton1Click:Connect(function()
			otherPlayer.PlayerGui.MainGui.GiveFrame.Visible = false
			tool.Parent = otherPlayer.Backpack
			print("request really done")
			player:WaitForChild("leaderstats").Points.Value += 1
			-- this part is broken. it kinda 'overlaps' with the same thing being fired again  ^
		end)
		otherPlayer.PlayerGui.MainGui.GiveFrame.Decline.MouseButton1Click:Connect(function()
			otherPlayer.PlayerGui.MainGui.GiveFrame.Visible = false
		end)
	else
		
	end
end)

this causes to give the player 2 points after its given 2 times, 3 times after the third time, and so on! I just need the function to restart after the button is clicked.

You could try just disconnecting the events each time it’s triggered. I would really recommend refactoring your code though because this isn’t ideal.

Code:

local prompt = script.Parent

local connections = {}

prompt.Triggered:Connect(function(player)
	print("pluh")
	local otherPlayer = game.Players:GetPlayerFromCharacter(character)
	local tool = player.Character:FindFirstChildWhichIsA("Tool")
	
	if tool then
		for i, connection in connections do
			connection:Disconnect()
		end
		
		table.clear(connections)
		
		game.ReplicatedStorage.GiveRequest:FireClient(otherPlayer, player, tool)
		otherPlayer.PlayerGui.MainGui.GiveFrame.Visible = true
		
		table.insert(connections, otherPlayer.PlayerGui.MainGui.GiveFrame.Accept.MouseButton1Click:Connect(function()
			otherPlayer.PlayerGui.MainGui.GiveFrame.Visible = false
			tool.Parent = otherPlayer.Backpack
			print("request really done")
			player:WaitForChild("leaderstats").Points.Value += 1
			-- this part is broken. it kinda 'overlaps' with the same thing being fired again  ^
		end))
		
		table.insert(connections, otherPlayer.PlayerGui.MainGui.GiveFrame.Decline.MouseButton1Click:Connect(function()
			otherPlayer.PlayerGui.MainGui.GiveFrame.Visible = false
		end))
	end
end)
1 Like

no idea how that works, just copied and pasted the code and it worked. imma look into it later. thanks!

I first made a table called connections. Then, I store both .MouseButton1Click functions in that table. Every time the prompt is triggered, I disconnect all of the functions and clear the table. If you need any more explanation, feel free to ask.

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