Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

8 comments

0

It’s script:Destroy(), not script:remove()

0

It’s script:Destroy(), not script:remove()

0

You need a wait before the end

0

even with the wait it still does not work

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()

0

im confused on what im doing wrong

0

The indents are maybe confusing the script. Try removing an indent on your "if #player == 0 then" statement. Hopefully that works!

0

OH YEAH! If you're removing an indent on the if statement remove an indent on the "end" on line 10 as well.

1 answer

✓ Accepted answer

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

This discussion is preserved as it was. New answers, comments, and votes are closed.