Attempt to index Nil with 'Character' Roblox seat animation script

So I want to understand how to get the Character in a Script, every time I have so much trouble with this and never find a way to fix it.

Problem:
Whenever I load into the game it gives me the error: Workspace.VehicleSeat.Script:7: Attempt to index nil with 'Character’

I have looked for solutions on Youtube and the Developer Hub, and I cant find a fix, or any hints to what could be the problem.

I am trying to make a script where when you are seated on a Vehicle Seat it plays an animation.

This is the Code:

-- Variables
local PushSeat = script.Parent
local Players = game:GetService("Players")

-- Player Variables
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")

-- Animation Variables
local Animation = PushSeat:WaitForChild("Animation")
local AnimationTrack = Humanoid:LoadAnimation(Animation)


Player.Seated:Connect(function()
	AnimationTrack:Play()
end)

Any explanations, Hints or Help to what could be the problem would be appreciated, thank you!

Server scripts can not access LocalPlayer. You will want to listen for an occupant change within the seat and apply the animation from there. The occupant of the seat will ALWAYS be a humanoid (if there is one).

-- Variables
local PushSeat = script.Parent

-- Animation Variables
local Animation = PushSeat:WaitForChild("Animation")
local AnimationTrack

PushSeat:GetPropertyChangedSignal("Occupant"):Connect(function()
	if PushSeat.Occupant then
		AnimationTrack = PushSeat.Occupant:LoadAnimation(Animation)
		AnimationTrack:Play()
	else
		AnimationTrack:Stop()
	end
end)
2 Likes
local Seat = script.Parent
local Animation = Seat:WaitForChild("Animation")
local Track

Seat:GetPropertyChangedSignal("Occupant"):Connect(function()
	local Humanoid = Seat.Occupant
	if Humanoid then
		local Animator = Humanoid:WaitForChild("Animator")
		Track = Animator:LoadAnimation(Animation)
		repeat task.wait() until Track.Length > 0
		Track:Play()
	else
		if Track then
			if Track.IsPlaying then
				Track:Stop()
			end
		end
	end
end)