What if using :Wait() on an event that will never be fired?

image

That code waits for the CharacterAdded event to be fired
What if I stop the player’s character from spawning through another script

Will it wait forever? How bad is that?

The thread would be yielded forever

2 Likes

It’s best to avoid cases like that where scripts are stuck waiting forever, especially if it’s a server script but you should avoid doing so in LocalScripts as well

For CharacterAdded if there’s going to be a long period of time before the character loads or a chance where the character doesn’t load I’d suggest doing this instead of using :Wait()

player.CharacterAdded:Once(function(character)

end)

This won’t yield the thread and the code inside will only run once with the connection disconnecting itself automatically afterwards

2 Likes

Use an or with it …
local Character = player.Character or player.CharacterAdded:Wait()

1 Like

Unfortunately if the character is prevented from loading, your script would still get stuck waiting infinitely

2 Likes

Hmm, do you still want this script to keep going even if so?
local Character = player.Character or player.CharacterAdded:Wait() or wait(10)
idk … looks bad to me. Character would be nil

Few ways around this really. Not sure what the scripts are doing in this case or what you want them to do. I guess the answer to your question is it will wait forever …

3 Likes

The problem is that the script should wait for the character to load, like what i gave there is an example because im not actually using CharacterAdded im used a different event that is from a part and the part could be gone before the event is fired, but if Once() doesn’t yield the thread the its gonna run the script without being ready.

Edit: I guess i could place the script inside the Once() but then if the part is destroyed wouldn’t it have a function connected that would never fire?

If a part is destroyed properly using :Destroy() or game.Debris:AddItem() then any connections associated to that part will be automatically disconnected and garbage collected

Although you also need to be careful about leaving accidental references to the part somewhere inside a different connection, as that would prevent the garbage collector from properly getting rid of the part even if you use the proper methods

The :Once connection is one of the least worrying connections though, so you shouldn’t experience any issues using it

Ohhh I see, I wasn’t aware of that, thx.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.