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

LocalPlayer.Character, a nil value. Why?

I made a button that's supposed to lead your character of a cliff, but it didn't work. This is the code I used.

plr = game.Players.LocalPlayer
char = plr.Character
click = game.Workspace.DieButton.Button.ClickDetector
click.MouseClick:Connect(function()
	char.Humanoid:MoveTo(game.Workspace.Die.Position)
end)

and it came out with an error: Players.marioman1932.PlayerScripts.Die:5: attempt to index global 'char' (a nil value) but it's not a nil value because I made a variable for it. Please help of why it says that. Edit: Yes this is in a local script.

5 comments

0

I think it depends if you're using a localscript, or a script. If this is a localscript, it has to work. If you are using a normal script, try click.MouseClick:Connect(function(player)

0

sorry i didnt read the edit, i honestly dont know why it isnt working

1

This is because you need to wait for the character to load

0

How do I do that? (post it in the answer bar)

0

I did but deleted it because @psudar's is better

1 answer

✓ Accepted answer

I think whats happening here is either:

A) The character hasnt been loaded in;

B) You might not be running this in a local script

--local script
plr = game.Players.LocalPlayer
char = plr.Character or plr.CharacterAdded:Wait()

click = game.Workspace.DieButton.Button.ClickDetector
click.MouseClick:Connect(function()
    char.Humanoid:MoveTo(game.Workspace.Die.Position)
end)

The reason this works is because or turns this into a conditional statement. If Player.Character comes back as nil, it goes to the next condition, which is the CharacterAdded event. It then halts the script from continuing until theres a character loaded in.

Hopefully that helps.

https://developer.roblox.com/en-us/api-reference/property/Player/Character

3 comments

0

Line two of his script would error if it's not a LocalScript. That's clearly not his problem.

1

Thanks! I like how you also explained why it worked!

0

Oof no problem. Also I didnt really think about line 1, its clearly a local script because it errors at line 2. Oversight on my part, most people would probably make the same mistake. Oh well, glad I helped you out.

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