Drive to earn cash problem

What is the issue? Include screenshots / videos if possible!
I have this code which all it does is, when you drive a car at a certain speed you earn cash, it works fine. the only odd problem is that it works fine when your character touches the (Vehicle-Seat).

However I added this new teleportation for (when you spawn in a car, your character teleports automatically for you) or (when you hold E on the ProximityPrompt) Prompting the error of.

Error: Workspace.cookpie416sCar.VehicleSeat.CarMoneyScript:23: attempt to index nil with ‘leaderstats’

But it’s easy to fix, just jump out the (Vehicle-Seat) and get back in and that fixes it. You likely see the issue at head, and if you don’t

Basically it’s gonna be annoying everytime you spawn in any car, especially if your trying to earn in-game Money and you don’t know why you aren’t earning any Money at all.


local player
local MetersDriven = script.MetersDriven

local Seat = script.Parent.Parent.VehicleSeat
local MoneyPrice = math.random(2,5)

script.Parent.Touched:Connect(function(hit)--Have to keep this in order to get the players leaderstats in order to increase Money/Cash.
	if hit.Parent:FindFirstChild('Humanoid') then
		player = game.Players:GetPlayerFromCharacter(hit.Parent)

	if Seat.Occupant then
		script.Parent.Parent.Front_lights.BrickColor ="Really red")
			while true do
			MetersDriven.Value = MetersDriven.Value + script.Parent.Velocity.Magnitude
			if MetersDriven.Value > 150 then
			MetersDriven.Value = 0
			player.leaderstats.Money.Value = player.leaderstats.Money.Value + MoneyPrice

Do not write entire scripts or design entire systems.

have you tried doing player:FindFirstChild(“leaderstats”)?

Yes, but with an error:
Workspace.cookpie416sCar.VehicleSeat.CarMoneyScript:23: attempt to index nil with ‘FindFirstChild’

Again easily fixable by jumping out and getting back in and it starts making money again.

in the touched event, if you put a print statement at the end printing the player, does it result in nil the first time?

Not at all, still does the same thing.

It sure does print my name a lot when touching the (Vehicle-Seat)