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

Why does my "random player" not reset?

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

1 comment

2

put local Players = game.Players:GetPlayers() between lines 7 and 8 so that the variable gets updated

2 answers

3 comments

0

Yes I did, it only selects me lol

0

did everyone connected when the 15 seconds timer went down?

0

its just math.random is not really random some times

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!

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