Question about events and threading

Hey there, so to start off, I think I understand what a thread is, but if what I’m asking here does not match up with the definition of threads, please forgive of that and feel free to correct me.

With that, so I was just wondering about this for efficiency. So I have a game function that I call when I want to start the game. Within that same function I initialize a few events, such as the Died event on each participating player’s humanoid, and on a ClickDetector. Now, I wonder if it’s bad practice to do these things, or if these events will end when the original thread stops running? (the game function.)

Sorry if this is poorly worded, I could clarify a bit if needed. Thanks for reading!

4 Likes

You have to explicitly disconnect the events, unless the object is destroyed.

But since the humanoid dies, for every player that survives, you would have to disconnect. Otherwise the next round you could end up creating an extra connection.

2 Likes

That’s what I originally thought. Thanks for that info! Will do.

Hello C_Sharper!

First off, events don’t yield a script. They just give the certain event a callback, that’s it.

Clarifying Threads

Calling a function (unless wrapped in a spawn or a coroutine) is not making a new thread. When you make a script without the use of spawns are coroutines, it is one thread. You can tell like this:

function testFunc()
    while true then
        print("yes")
        wait(5)
    end
end

testFunc()
print("no")

That print(“no”) will never get reached as the function runs forever.

Now if you are asking if not :Disconnecting events is bad practice, it has never bitten me in the behind. Unless you are connecting thousands of events, I don’t think it will have a bad impact on the game. Now if you are worried that leaving a LocalScript in the character with connected events when they die is bad, you shouldn’t be worried as when the script gets destroyed, events will disconnect (@Darkmist101 touched on this).

Edit: Oof @Darkmist101 beat me by a milestone… gg

1 Like

It’s always good practice to not leave around what you don’t need anymore. Destroy objects you’re not using anymore or disconnect connections that you don’t need anymore. In some cases, you need to disconnect events (i.e. DataStore OnUpdate).

Connections are also capable of leaking memory, so that should be a red flag to disconnect unnecessary connections.

2 Likes

Well, my code workflow is basically one main script and a bunch of modules. I connect events and I don’t really need to disconnect as I need those events for basically the remainder of the game. I guess it was bad of me to automatically assume he was using the same workflow as me; sorry.

I haven’t worked with DataStores intensively yet, but thanks for letting me know about that!

1 Like