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

Teleportation script | attempted to index field 'Character' (a nil value)?

I am trying to make a** teleportation script** that will teleport all of the players to a random spawn location on my map. The 'map' variable is already defined earlier in the script. My error is: attempted to index field 'Character' (a nil value)

local MapPlayerSpawns = map.SpawnLocations:WaitForChild("PlayerSpawns"):GetChildren()
	function tp()
		local Players = game.Players:GetPlayers()
		for i = 1,#Players do
			local randomPTP = math.random(1,#MapPlayerSpawns)
			local IndSpawn = MapPlayerSpawns[randomPTP]
			Players[i].Character.HumanoidRootPart.CFrame = IndSpawn + Vector3.new(0,5,0) -- I get my error on this line.
		end
	end
	tp()

2 answers

✓ Accepted answer

All your error means that is the Character didn't load in time the script dead, simple fix with WaitForChild().

local MapPlayerSpawns = map.SpawnLocations:WaitForChild("PlayerSpawns"):GetChildren()

local function tp() -- no need for the for i = loop
	for _,plr in pairs(game.Players:GetPlayers()) do
		local indSpawn = MapPlayerSpawns[math.random(1, #MapPlayerSpawns)]
		plr.Character:SetPrimaryPartCFrame(indSpawn.CFrame + Vector3.new(0, 5, 0)) --forgot .CFrame, hence it wasnt set CFrame
	end
end

7 comments

0

I did that and the error doesn't appear again but now I get a yellow/orange error saying: Infinite yield possible on 'Players.N43FGXL:WaitForChild("Character")'

0

Try that

0

attempt to index local 'plr' (a nil value) | Now I get this error...

0

Updated

0

Still get error...

0

This script works fine for me. It's probably your internet acting up.

0

My plr variable was displaying as 'nil'. I now fixed it. Thanks for help, I'll still accept your answer.

Put an object value inside the backpack of the player and make a script that sets that object value to the character of the player. Then you can take that object value as reference to the player character.

A script that sets the character of the player to the object value could be for example when the player spawns he fires a RemoteEvent from a local script and sends his character to a server script which sets the object value to the character.

local script

repeat wait() until game.Players.LocalPlayer.Character -- waits until the character is loaded

local Player = game.Players.LocalPlayer
local Char = Player.Character


game.ReplicatedStorage.RemoteEvent:FireServer(Char)


normal script


game.ReplicatedStorage.RemoteEvent.OnServerEvent:Connect(function(Player,Char)
	Player.Backpack.ObjectValue.Value = Char
end)


1 comment

0

My plr variable was displaying as 'nil'. I now fixed it. Thanks for help, I'll still upvote your answer.

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