MouseButton1Click event not functioning properly in BindableEvent

Hello!

I am experiencing an issue with my dialog. When the remote event is triggered and the button is clicked, the text is supposed to be displayed in a specific order. However, after the first time, the dialog ignores some of the messages in the dialog.

The dialog has 3 messages, and this is how it gets displayed:

The first time the dialog is fired it shows everything, and it works as intended.
The second time it only shows the first two.
And the third time it only shows the first message.

I’ve been told it’s possible that the issue is caused by the MouseButton1Event being in the BindableEvent function, but I would be unsure of how to fix it.

My code is below. Can anyone suggest a solution to this problem?

StartDialogRE.Event:Connect(function()
	local index = 1

	local questModule

	questModule = require(Template:FindFirstChild("Template"..template))

	script.Parent.Text = questModule.Dialog[status][index] 

	local maxNumbers = #questModule.Dialog[status]

	script.Parent.MouseButton1Click:Connect(function()
		if index > maxNumbers then
			--Once the player has finished the dialog
			print("Done")
			index = 1
		else
			--Continuing the dialog
			script.Parent.Text = questModule.Dialog[status][index]
			index = index + 1
		end
	end)
end)

The full code is not shown for protection and clarity purposes, but the provided code still exhibits the problem.

When the mouse button is clicked, it should display the second message, then the third, then the second and third again. Instead, it only shows the second message and then stops.
I would greatly appreciate any help!

So the problem here is you’re creating the MouseButton1Click handler every time the event is called. I’m not really sure how your code works, but there’s a few ways to fix this:

  1. Cleanup:
    local buttonHandler – this will be the MouseButton1Click handler
    script.Parent.MouseButton1Click:Connect(function()
    if buttonHandler then – cleanup the old handler
    buttonHandler:Disconnect()
    end
    buttonHandler = script.Parent.MouseButton1Click:Connect(function()
    – your code here
    end)
    end)
  2. Using a local variable:
    local index = 0
    script.Parent.MouseButton1Click:Connect(function()
    index = index + 1
    if index > #questModule.Dialog[status] then
    index = #questModule.Dialog[status]
    end
    – your code here
    end)
  3. Using a boolean:
    local index = 0
    local running = true
    script.Parent.MouseButton1Click:Connect(function()
    if running then
    index = index + 1
    if index > #questModule.Dialog[status] then
    index = #questModule.Dialog[status]
    running = false
    end
    – your code here
    end
    end)