How to select a random player in the server and move them somewhere?

Hello, i tried to make a script where the script picks one of the players in a server and moves their position somewhere else.
the problem im facing is the players registered in game.players does not contain a humanoid,
for me when a player joins a new instance is created in game.players and game.workspace.
Both of those are registered in your name:
image
The model thats in workspace contains all the information/humanoid etc i need for this script to work.
but i use a GetChildren in the game.players, but it wont work in workspace because it will get all the models and parts. How do i get this script to work?

How about you try getting all the models in workspace and check if you have find them in game.Players and then insert them into a table, and then after youve found all of them do that math.random stuff to select a random players character

1 Like

Can you give me a idea, i took a long break of scripting but i dont know how to check if a name in workspace is also in for example players.

Yeah of course so basically this code loops through workspace and then it checks if the names of the models are in game.Players meaning that they indeed a player’s Character and then we get a randomPlayersCharacter

local playerCharacters = {}

for _, character in pairs(workspace:GetChildren()) do
	if game.Players:FindFirstChild(character.Name) then
		table.insert(playerCharacters, character)
	end
end

local randomPlayersCharacter = playerCharacters[math.random(1, #playerCharacters)]
print(randomPlayersCharacter)

Output

image

1 Like

ServerScriptService.Script:9: invalid argument #2 to ‘random’ (interval is empty) i get this error.

Did you just slap it into a server script or do you have it running at a certain time in a script?

The error is happening because there are no characters in the playerCharacters table

1 Like

slap it into a server script. do i need to make a loop or something?

Well I thought you had already some sort of code that would run this code at a certain time, if your just trying to test it your going to have to but a task.wait(2) so that the characters can load in before the script runs

1 Like

i did this:

task.wait(2)
local playerCharacters = {}

for _, character in pairs(workspace:GetChildren()) do
	if game.Players:FindFirstChild(character.Name) then
		table.insert(playerCharacters, character)
	end
end

local randomPlayersCharacter = playerCharacters[math.random(1, #playerCharacters)]
print(randomPlayersCharacter)

still getting the same error.

It worked for me but I waited 5 seconds try changing it to a longer wait time

1 Like

Never mind, it works find, i just realised i had like 20 tabs open making it really slow to load and it needed more than 2 seconds to load my character in.

1 Like

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