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

Error saying that character is nil value, i get this error a lot?

05:09:28.760 - Players.Gomenasa1.Backpack.Tool.LocalScript:2: attempt to index field 'Character' (a nil value)

I'm trying to get to the torso using:

local torso = game.Players.LocalPlayer.Character.Torso

any and all help appreciated!

2 answers

✓ Accepted answer

This error is caused by the character not actually existing yet. Since there is no character game.Players.LocalPlayer.Character is in turn, nil. So basically your script does this:

local torso = nil.Torso

which is explained by your error, attempt to index field 'Character' (a nil value)

The Fix

To add a fix to your script, we're going to make the script yield till it gets a character if one isn't already there. We will be using the Player.CharacterAdded event which gives us the character itself as its return value.

Using CharacterAdded

Since we want our script to yield we're going to use :Wait() on our connection, so it makes the script wait until the event is fired. So we get something like this:

local plr = game.Players.LocalPlayer
local character = plr.CharacterAdded:Wait()

Adapting for preexisting characters

This would work all well and good if it weren't for that fact that the character might already be there. So our basic logic should be: if the player has a character then return the character, if not then wait for the character to be added and return the newly formed character. We adapt our script do in one line of logic:

local plr = game.Players.LocalPlayer
local character = plr.Character or plr.CharacterAdded:Wait()

Since the or operator goes to the next if the current one is false or nil, we can utilize the plr.Character property. Our script at this stage checks if there's a preexisting character, returns it, if there's no character, it yields and returns the new character.

That's all! So your own fixed script would look something like this:

local plr = game.Players.LocalPlayer
local character = plr.Character or plr.CharacterAdded:Wait()
local torso = character:WaitForChild("Torso", 10)

Note: Searching for the child "Torso" will only work if there player's character is R6 since R15 has an UpperTorso and a LowerTorso but no "Torso" body part.

That's it from me!


Hope this helped, feel free to ask any questions or point out any mistakes below!

local torso = game.Players.LocalPlayer:WaitForChild("Character").Torso

You're welcome.

Edit: Sorry, this solution is wrong. See Ankur_007 answer below... My bad :(

3 comments

0

ooo that makes more sense, ty..

0

Actually that won't work sense Player.Character is a property and not a child, rendering :WaitForChild("Character") useless.

0

it was working at first but as I got into the script it stopped, eek.

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