How to stop a function from a different thread?

Not sure if ‘thread’ is the right word but it’s all I could think of.

local function a()
    wait(2)
    print"Hey"
    wait(6)
    print"Hey2"
end

Think of this script like a cutscene, if the player presses E, it’ll stop the cutscene.

UIS.InputBegan:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.Keyboard then
		if input.KeyCode == Enum.KeyCode.E and not gameProcessed then
			-- stop a()
		end
	end
end)

Without using a boolvalue and a bunch of if-statements to detect if the player pressed E, how else could I go about stopping a() while it’s running?

Functions can be disconnected by using the :Disconnect() function.

UIS.InputBegan:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.Keyboard then
		if input.KeyCode == Enum.KeyCode.E and not gameProcessed then
            a:Disconnect()
		end
	end
end)

Disconnect() “disconnects” a function from an event, meaning from then on after using Disconnect() the function will no longer be called when the event fires. It doesn’t stop a function once it’s already been called.

1 Like

Have you tried utilizing coroutines i think that might be able to help you

Well it isn’t supposed to be a loop, so I’m not sure if it would help me.