ContextActionService function calling by itself

I am making a dialogue system for my game. Currently, I am making a function where ContextActionService detects a click or a touch and speeds up the dialogue, this partly works, however at the end of each line of dialogue, the function calls by itself with even no input. Any help would be appreciated, thank you. If you have any questions about the code or anything else, please ask me.

Here is the code:

local speaking = false
local indialogue = false
local speaker
local cooldown = false

local function sound(id)
	local sound = Instance.new("Sound", dialogueUi)
	sound.SoundId = "rbxassetid://"..id
	sound:Play()
	sound.Ended:Connect(function()
		sound:Destroy()
	end)
end

local speaking = false
local indialogue = false
local speaker
local cooldown = false

local function dialogue(name, text, speed, colour, soundId, inspeech)
	if speaking and not inspeech then return end
	if cooldown then return end
	speaking = true
	speaker = name	
	local skipped = false
	dialogueUi.Speaker.Text, dialogueUi.Speech.Text, dialogueUi.Speech.MaxVisibleGraphemes,
		dialogueUi.Speaker.TextColor3, dialogueUi.Speaker.TextStrokeColor3, dialogueUi.Skipping.Visible = name, text[1], 0, colour, colour, false
	
	if not indialogue then
		local tween = ts:Create(dialogueUi, TweenInfo.new(1, Enum.EasingStyle.Sine, Enum.EasingDirection.Out), {Position = UDim2.new(0.5, 0, 0.65, 0)})
		tween:Play()
		tween.Completed:Wait()
	end
	indialogue = true
	cas:BindAction("Skip", function()
		skipped = true
		dialogueUi.Skipping.Visible = true
		cas:UnbindAction("Skip")
	end, false, Enum.UserInputType.MouseButton1, Enum.UserInputType.Touch)
	
	for i = 1, text[1]:len() do
		dialogueUi.Speech.MaxVisibleGraphemes = i
		
		if text[1]:sub(i, i) ~= " " then
			if not skipped then
				sound(soundId)
				if text[1]:sub(i, i) == "," or text[1]:sub(i, i) == "." then
					wait(0.5)
				else
					wait(speed)
				end
			else
				task.wait()
			end
		end
	end
	
	cas:UnbindAction("Skip")
	
	wait(3)
	
	if #text == 1 then
		local tween = ts:Create(dialogueUi, TweenInfo.new(1, Enum.EasingStyle.Sine, Enum.EasingDirection.Out), {Position = UDim2.new(0.5, 0, 1.1, 0)})
		tween:Play()
		tween.Completed:Wait()
		speaking = false
		indialogue = false
		cooldown = true
		wait(1)
		cooldown = false
	else
		table.remove(text, 1)
		dialogue(name, text, speed, colour, soundId, true)
	end
end

events.DialogueClient.OnClientEvent:Connect(function(name, text, speed, colour, soundId, inspeech)
	dialogue(name, text, speed, colour, soundId, inspeech)
end)
1 Like