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

How do you make a "Character" not nil???

I made a script where a mesh part is supposed to be inside a new players torso whenever a new player joins. The thing is, when I hit play, it says "ServerScriptService.Script:4: attempt to index field 'Character' (a nil value)". Heres the script: (I put it in a script, but also tested it in a local script, but I hit Play and the local script did nothing.)

game.Players.PlayerAdded:connect(function(player)
	local meshclone = game.ServerStorage.MeshPart:Clone()
	local plr = game.Players.LocalPlayer
	meshclone.Parent = plr.Character.Torso
end)

1 answer

✓ Accepted answer

You must wait for the character to load in before reading it. You can wait for the CharacterAdded event of the player to fire with player.CharacterAdded:wait()

Because the character may have already loaded, this can also be improved by skipping the wait just in case the character has already loaded in so that the thread does not yield unnecessarily.

game.Players.PlayerAdded:connect(function(player)
	local meshclone = game.ServerStorage.MeshPart:Clone()
	local plr = game.Players.LocalPlayer
	local char = plr.CharacterAdded:wait() or plr.Character
	meshclone.Parent = char.Torso
end)

I also noticed you are defining a new variable called plr in the function which is unnecessary if this is in a server script as the PlayerAdded event returns the player instance. If this is in a local script, then there is no need to connect a listener function to the PlayerAdded event as a local script will automatically run when the local player has joined.

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