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

Script gets an error when players join while teleporting players?

When i test my game with multiple fake players, this shows up in the output:

ServerScriptService.MapChanger/Intermission:26: attempt to index nil with 'MoveTo'

MapChanger/Intermission is the name of my script, here is the block of code:

	local spawns = chosenMap.Spawns:GetChildren()
	for _, Player in pairs(game:GetService("Players"):GetPlayers()) do
		local SelectedPart = spawns[math.random(1, #spawns)]
	    Player.Character:MoveTo(SelectedPart.Position)
	end

One possible reason I think this is occurring may have to do with players not being completely loaded in when they join the game. Overall, it's really annoying and when the error occurs, the game can no longer function as this is the main game runner.

Merely unrelated, but I thought I'd bring it up anyway, was a suggestion by others that I should change MoveTo to setPrimaryPartCFrame() but I cannot seem to get it to work.

To some, this block may seem familiar because I posted here merely a day ago, I thought it was worth bringing up so here I am. To anyone that recognises me or this script, sorry for my impatience, thank you.

2 answers

You'll need to wait for each character to load in. You can do this by using Player.CharacterAdded:Wait(), which waits until the character for that player has been set. You may also want to use WaitForChild on their HumanoidRootPart.

Player.CharacterAdded:Wait() -- yield until theyre added
local root = Player.Character:WaitForChild("HumanoidRootPart")
Player.Character:MoveTo(...) -- move them

3 comments

0

The block looks good so far, ill test it out when i get the time again, thanks. What’s your input on setPrimaryPartCFrame() btw?

0

MoveTo does overlap checking, meaning that if you were to try and use it to teleport the player into a large brick, it would shift the player up so it does not get stuck inside. SetPrimaryPartCFrame would place them inside of the block, not caring about overlaps.

0

Okay so I still get this error when playtesting, it only occurs while someone's player is still loading in and joining. Additionally, adding Player.CharacterAdded:Wait() at the beggining just seems to stall forever, please help with how I should lay the script out.

You are taking their character before it exists. Try doing this

local spawns = chosenMap.Spawns:GetChildren()
for _, Player in pairs(game:GetService("Players"):GetPlayers()) do
    local SelectedPart = spawns[math.random(1, #spawns)]
    if player.Character then
	Player.Character.HumanoidRootPart:MoveTo(SelectedPart.Position)
    end
end

1 comment

0

"player" (lowercase) is unidentified, am I changing it to "Player", i get an error when i do so, "MoveTo is not a valid member of Part".

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