How do I end a thread from a script?

To answer your question, you can call, resume, and stop a thread by using coroutines. Similar to spawn, in that they both run a function in their own seperate threads. The difference being you can have more control over coroutines.

local thread = coroutine.create(function() --Create a coroutine
    --Put the loop here
end)

coroutine.resume(thread) --Play the coroutine

You can also just do

local thread = coroutine.wrap(function() --Creates and runs the coroutine
    --Put the loop here
end

Now, to stop or yield a coroutine do

local thread = coroutine.wrap(function()
     while wait() do
        if not script.Parent then
            coroutine.yield() --Yields the coroutine. You can still resume the thread if you want.
        else
            --Do stuff
        end
    end
end

On the other hand, you could just use the break keyword to break the loop if the parent of the script is equal to nil, but coroutines also work. :slight_smile:

Now, do I think this is the best way to go about connecting a click detector using a while loop? No, this is an inefficient way to do this. I recommend using a for loop and looping through the parent of the click detectors and connecting like that, and then using a ChildAdded event to connect other click detectors that are added.

4 Likes