The player's character is not always guaranteed to exist, which is why you need to set up a bunch of things in order to make sure you always have the character.
First off, you need to make sure that the character exists when you're first getting it. If it doesn't exist, then wait until it is added to the workspace.
2 | local PLAYERS = game:GetService( "Players" ) |
3 | local Player = PLAYERS.LocalPlayer |
4 | local Character = Player.Character or Player.CharacterAdded:Wait() |
However, we face an issue when the character dies. The character is destroyed when it dies and is replaced with a new character, so we need to update the Character variable when the character is added back to workspace.
2 | Player.CharacterAdded:Connect( function (character) |
Now you should see that the character updates every time it is respawned. You also have to make sure that the character exists whenever you reference it, or things will go wrong. Here's an example script that sets the character's walkspeed to a random number every time it's respawned.
02 | local PLAYERS = game:GetService( "Players" ) |
03 | local Player = PLAYERS.LocalPlayer |
04 | local Character = Player.Character or Player.CharacterAdded:Wait() |
05 | local Humanoid = Character:WaitForChild( "Humanoid" ) |
07 | Player.CharacterAdded:Connect( function (character) |
09 | Humanoid = Character:WaitForChild( "Humanoid" ) |
10 | Humanoid.WalkSpeed = math.random() * 64 |
If you want a quick and dirty way of doing it, though, just make a LocalScript parented to StarterCharacterScripts, which should update every time the character is respawned.
2 | local Character = script.Parent |
3 | local Humanoid = Character:WaitForChild( "Humanoid" ) |
4 | Humanoid.WalkSpeed = math.random() * 64 |
I prefer this method because it doesn't involve RBXScriptSignals, which are a bit dirty, but many prefer the former method, so do what you want.