When a random player selected it prints nil

i got a probelm i have this intermission system that will select a random player to apply some role to it but the problem is that i am trying to print the player’s name but it returns nil

so please just help my by correcting my script or even putitng an entire new script

my goal is to make an intermission system that selects a random player to assign a role to him much like murder mystery it assigns a role to a random player like murder or sheriff

local players = game.Players

local RequiredPlayers = 2
	
	
	local CurrentPlayers = 0
	
repeat
	
	task.wait(1)
	
	local playersinsession = game.Players:GetPlayers()
	
		CurrentPlayers = #game.Players:GetPlayers()
		
		RandomPlayer = playersinsession[math.random(0,#playersinsession)] -- i put a 0 so when no players are loaded the value stilll wont be bigger than the second value but i am pretty sure that this is what causing the problem
		
		
		print("Gathering players..")		
		
	until CurrentPlayers >= RequiredPlayers 
	
	-- Wait before teleporting
	task.wait(1)
	-- Teleport (just a example)
	print("selecting Player")
	
	print(RandomPlayer)

Try replacing 0 with 1, in Luau, tables start with 1 so this guarantees that the player you get exists.
Also I recommend you explore Players.PlayerAdded to count your players rather than looping.

your right but the problem is that when i make it a 1 the script will run before the players spawn therefor it will result in this error : invalid argument #2 to ‘random’ (interval is empty)

the interval is the players there is no players in the table, the table cant be randomed because nothing is in the table

Then generate your random player once CurrentPlayers >= RequiredPlayers

where specifically should i put it in the script? after the until ?

This part should work.

until CurrentPlayers >= RequiredPlayers 
	
task.wait(1)

local playersinsession = game.Players:GetPlayers()
CurrentPlayers = #game.Players:GetPlayers()
RandomPlayer = playersinsession[math.random(0,#playersinsession)]

print("selecting Player")
print(RandomPlayer)

appreciate it bro thankfully it worked the weird thing is that i have tried this solution before but it didnt work but anyways thanks for your help

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.