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

Why does my "random player" not reset?

Asked by 1 year ago
Edited 1 year ago

I have a problem, I am making a script which teleports a random player to a place, but the first time to random player gets selected, it never changes again, so its always the same person that gets teleported.

wait(15)
local Players = game.Players:GetPlayers()
local ob1 = workspace.Scorer.Orange_25.Touch
local ob2 = workspace.Scorer.Red_10.Touch
local ob3 = workspace.Scorer.Yellow_50.Touch

while true do
    local Randomplayer = Players[math.random(1, #Players)]
    print(Randomplayer)
    Randomplayer.Character.HumanoidRootPart.CFrame = CFrame.new(73, 98, 33)
    wait(14.9)
    if ob1.Value == false and ob2.Value == false and ob3.Value == false then
        Randomplayer.Character.HumanoidRootPart.CFrame = CFrame.new(66, 10, -287)
    end
    wait(0.1)
end

Help would be really appreciated, thank you. (Yes I did play the game with friends too.)

2
put local Players = game.Players:GetPlayers() between lines 7 and 8 so that the variable gets updated imKirda 4491 — 1y

2 answers

Log in to vote
0
Answered by
Puppynniko 1059 Moderation Voter
1 year ago
Edited 1 year ago

try playing the game with "Friends" : ) spam the run button and you'll see the output change https://scriptinghelpers.org/lua#DYewxghsAEAKwQJ4FMBOBnaBeaBvAUNEdAETxJoCMJANIcWQiqgEwn4C+++ADqgJYA7AC4AKcs3QBtALYRhACwB0qCIIAmIGaMo1oAYglp0ASgC6JoA

0
Yes I did, it only selects me lol OreyTheOre 52 — 1y
0
did everyone connected when the 15 seconds timer went down? Puppynniko 1059 — 1y
0
its just math.random is not really random some times Puppynniko 1059 — 1y
Ad
Log in to vote
0
Answered by 1 year ago

Variable Persistance

Variables do not change unless you reassign them. In this case, the variable Players does not update to the new players.

Here is an example:

-- Player1 joins
local plrs = game.Players:GetPlayers()
print(plrs) --> {Player1}

-- Player2 joins
print(plrs) --> {Player1}
plrs= game.Players:GetPlayers()
print(plrs) --> {Player1, Player2}

As you can see, plrs will always hold Player1 and not include Player2 until plrs is re-assigned to the new list of players.

Solution

You should update the Players variable to get all the current players before attempting to select a random player.

-- since :GetPlayers() is a table itself, you can call it like this
local Randomplayer = game.Players:GetPlayers()[math.random(1, #game.Players:GetPlayers())]

-- you can also update the variable before using it
local Players = game.Players:GetPlayers()
while true do
    Players = game.Players:GetPlayers()
    local Randomplayer = Players[math.random(1, #Players)]
end

Good luck!

Answer this question