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

My spawning script doesn't work! It isn't spawning the character correctly?

game.Players.LocalPlayer.Character.Humanoid.Died:connect(function()
	wait(4.2)
	if game.Players.LocalPlayer.StageNum.Stage.Value == 1 then
		game.Players.LocalPlayer.Character.Torso.CFrame = CFrame.new(workspace.Stage1Spawn.Position) + Vector3.new(0,1,0)
	end
end)

Output

ServerScriptService.StageSpawning:1: attempt to index field 'LocalPlayer' (a nil value)

3 comments

0

What script is this code in and where is it located.

0

its a regular script and in serverscriptservice

1

LocalPlayer can only be used in a Local script

1 answer

Like frosty said, LocalPlayer can only be used in a LocalScript. LocalScripts run on the client, aka you. A normal script has no idea who the client is. Use CharacterAdded to know when you can move the player. If you try moving them after they die, you're just going to teleport their dead body. CharacterAdded fires after your character loads from a death or otherwise.

-- This would go in a normal script in ServerScriptService
local ws = game:GetService("Workspace")
local players =  game:GetService("Players")
local spawn_pos = ws:WaitForChild("Stage1Spawn").Position + Vector3.new(0,1,0)

local function player_joined(player)
	player.CharacterAdded:Connect(function(char)
		local stage_num = player:findFirstChild("StageNum")
		if stage_num and stage_num.Stage.Value == 1 then 
			char:MoveTo(spawn_pos)
		end
	end)			
end

 -- :connect() is deprecated, use Connect
players.PlayerAdded:Connect(player_joined)

-- Catch and connect all the players that PlayerAdded didn't when the script loaded.
for i,v in pairs(players:GetPlayers()) do 
	player_joined(v)
end

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