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