Iterating through each time a button is pressed

Text = {
    'Hello!',
	'Hows things?',
	'Thats good!'
}

function DialogueControl.speakingTo(character, stage)
	NPC = character
	
	for _, v in pairs(Text) do
		MainDialogue.Text = v
		repeat wait() until Continue
		print('Done')
	end
end

UserInputService.InputBegan:Connect(function(input, GPE)
	if GPE then return end
	
    if input.KeyCode == Enum.KeyCode[Settings.ControllerKey] or input.KeyCode == Enum.KeyCode[Settings.PCKey] then
		Continue = true
		Continue = false
	end
end)

My goal was that the MainDialogue would through each part of the Text table one bit a time each time the player pressed a button (E in this case) however, I can’t get the timing down.

Thought process being setting the continue to true for a split second would mean it’d be able to iterate to the next part of the table, but what I have got doesn’t do anything when I press E (even tho Continue is changing, it’s changing back to false too fast)

I tried adding a wait() between changing the Continue but that just ended up skipping the middle half of the Text table and going straight to the last one

1 Like

You should set the continue flag off right before you start checking for it being on. If you structure/design your code differently you might be able to get a solution that doesn’t involve polling constantly, but this should work.

function DialogueControl.speakingTo(character, stage)
	NPC = character
	
	for _, v in pairs(Text) do
		MainDialogue.Text = v
		Continue = false
		repeat wait() until Continue
		print('Done')
	end
end

UserInputService.InputBegan:Connect(function(input, GPE)
	if GPE then return end
	
    if input.KeyCode == Enum.KeyCode[Settings.ControllerKey] or input.KeyCode == Enum.KeyCode[Settings.PCKey] then
		Continue = true
	end
end)
1 Like

For what it’s worth, here is one way you could do it without polling.

function DialogueControl.speakingTo(character, stage)
	
	NPC = character
	local thread = coroutine.running()

	-- Connection is here because we have to access the main thread
	local conn = UserInputService.InputBegan:Connect(function(input, GPE)
		if GPE then return end
		
		if input.KeyCode == Enum.KeyCode[Settings.ControllerKey] or input.KeyCode == Enum.KeyCode[Settings.PCKey] then
			coroutine.resume(thread)
		end
	end)

	for _, v in pairs(Text) do
		MainDialogue.Text = v
		coroutine.yield() -- Wait for resume from inputBegan
		print('Done')
	end

	conn:Disconnect()
end
1 Like