Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why does this script work without while true do but does not work with while true do?

Asked by 5 years ago
Edited 5 years ago

This script picks a random player and then teleports them to the place but if the script finds no players the script deletes itself and prints No Players but then I added a while true do and I tested it but now it always says No Players even when there is a player. Can anyone help me?

Here is the script I used

local Players = game.Players
local player = Players:GetChildren()

while true do
    wait(5)
    if #player == 0 then
        print("No players.")
        script:Destroy()
        return
    end
    local pickedPl = player[math.random(1, #player)]
    wait()
    pickedPl.Character.Torso.CFrame = CFrame.new(109.5, 25.5, -95.5)
    print(pickedPl.Name)
end
0
It’s script:Destroy(), not script:remove() User#19524 175 — 5y
0
It’s script:Destroy(), not script:remove() User#19524 175 — 5y
0
You need a wait before the end SBlankthorn 329 — 5y
0
even with the wait it still does not work MasonTheCreeperYT3 74 — 5y
View all comments (4 more)
0
@SBlankthorn, you don't really have to do that. while loops don't crash as long as you have some type of delay. The delay is 5 seconds. The asker does not need another wait() saSlol2436 716 — 5y
0
im confused on what im doing wrong MasonTheCreeperYT3 74 — 5y
0
The indents are maybe confusing the script. Try removing an indent on your "if #player == 0 then" statement. Hopefully that works! Z0ggg 20 — 5y
0
OH YEAH! If you're removing an indent on the if statement remove an indent on the "end" on line 10 as well. Z0ggg 20 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

Problem: You are defining players at the start of the script instead of at the start of your loop.

Let me explain:

At the start of the game, there are usually 0 players. The script is defining players:GetChildren() when there's 0 players. Remember, variables are static, they only change if you redefine them. But if you define player after wait(5), it will change.

Fixed script:

local Players = game.Players


while true do
    wait(5)
    local player = Players:GetChildren()
    if #player == 0 then
        print("No players.")
       break --Stops the loop
    end
    local pickedPl = player[math.random(1, #player)]
    wait()
    pickedPl.Character.Torso.CFrame = CFrame.new(109.5, 25.5, -95.5)
    print(pickedPl.Name)
end
Ad

Answer this question