Position `nil` after moving 19 times

local speed = 1
local car = game.Workspace.Car

-- Check if the Car object exists and has a PrimaryPart
if car and car.PrimaryPart then
	while true do
		car:MoveTo(car.PrimaryPart.Position + Vector3.new(speed, 0, 0))
		print("Moved car model to:", car.PrimaryPart.Position)
		wait(0.1)
	end
else
	warn("Car object or PrimaryPart not found.")
end

The first 19 times it moves, it is fine.
After the part moves 19 times, it gives me the error

Workspace.Car.Script:7: attempt to index nil with 'Position'  -  Server - Script:7

Any idea how to fix?

Is your car being deleted? Do you have streaming content enabled?

it would tell me Car object or PrimaryPart not found. if the car is getting deleted, and it doesn’t

this error message means that you can’t get the position from the variable(car/primary part) because it is nil.

Variable.Position -- If you get that error message from this line then Variable is nil
-- attempt to index nil with 'Position'

No the warning should never run, you have a while true do before it with no break; if it ever enters that while loop it will never run any more code in the same thread.

You have to nest the if statement in the loop in order for it to update each time you try to move the car:

local speed = 1
local car = game.Workspace.Car

-- Check if the Car object exists and has a PrimaryPart
while true do
	if car and car.PrimaryPart then
		car:MoveTo(car.PrimaryPart.Position + Vector3.new(speed, 0, 0))
		print("Moved car model to:", car.PrimaryPart.Position)
		wait(0.1)
	else
		warn("Car object or PrimaryPart not found.")
	end
end
1 Like

I found out the issue, I made the primaryPart unanchored so it slowly fell out the map, so I had to anchor it and move the if statement, and it works! Thanks though

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.