How to stop While Loop inside CharacterAdded after each spawn?

How would I make the While loop below to stop once a player is respawned again? char ~= nil doesn’t work

plr.CharacterAdded:Connect(function(char)
     while char ~= nil and plr ~= nil and wait(5) do --I want this loop to break when a new character is spawned
           print("Bla")
     end
end)

You could save a tick() value once per spawn and check it in the loop to see if it’s still the same

2 Likes

Option 1:

plr.CharacterAdded:Connect(function(char)
     while wait(5) and plr.Character == char do
           print("Bla")
     end
end)

Option 2:

plr.CharacterAdded:Connect(function(char)
     while wait(5) do
          if plr.Character ~= char then
               break
          end
           print("Bla")
     end
end)

I also removed the char ~= nil and plr ~= nil because those should never become nil unless you explicitly set them to nil. Variables referencing instances do not become nil when those instances are removed or destroyed.

4 Likes

If you use playeradded, it will only happen for the first time

while wait() do end will not end, because wait function will return a value. Instead

Player.CharacterAdded:Connect(function()
    repeat wait() until Player.Character
end)

It will end when combined with an and. For example, wait() and false gives false.

Additionally, your example will only end when the player’s character is nil.


What you say is technically correct, though, because while wait() do can’t end. Beartikal isn’t using while wait() do. He’s using while wait() and ... do, which can end.

It’s possible you only meant your example code as a very incomplete example and expect Beartikal or others to implement it fully, but I can’t tell. Here’s a more complete example using repeat that does what Beartikal wants to do:

Player.CharacterAdded:Connect(function(character)
    repeat
        print("Bla")
        wait()
    until Player.Character ~= character
end)