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