Help with the error message: Workspace.CoolPart.Script:24: attempt to index nil with 'Position'

Hello. I am a new Roblox dev trying to learn how to code. My knowledge is very limited, but I do know enough to make the script you see a bit further down. My goal is to create a part that will teleport you to the other side of it when you touch it, but for some reason it only partly works.

Here’s the problem. When I first touch the part, it works as it should. but when I touch it a second time, I get this error message:

Workspace.CoolPart.Script:24: attempt to index nil with ‘Position’

After looking it up, I now think I know what this error message means, but I still don’t know how to solve it. The reason why I am so confused is because it worked once, but when I try again it doesn’t work. And before anyone asks, the code does work when I try it a third time. and then when I try a forth time it doesn’t work.

Here’s the script:

local part = script.Parent
local monkey = true
local coolDown = true

part.Touched:Connect(function(otherPart)
	local humaniod = otherPart.Parent:FindFirstChild("Humanoid")
	local RootPart = otherPart.Parent:FindFirstChild("HumanoidRootPart")
	
	if humaniod then 
		if coolDown == true then
			if monkey == true then
				monkey = false
				coolDown = false
				RootPart.Position = RootPart.Position + Vector3.new(0, 0, 10)
				
				wait(1)
				coolDown = true
			end
		end
		
	else
		if coolDown == true then
			monkey = true
			RootPart.Position = RootPart.Position + Vector3.new(0, 0, -10)
			
			wait(1)
			coolDown = true
		end	
	end
end)

So, does anyone know how to fix this?

The error, which is occuring on the following line

means that RootPart is nil (doesn’t exist).

This would make sense, as if humanoid is nil (which is the only way that this statement is reached), then HumanoidRootPart will also be nil (as it means it isn’t a player’s character).

Looking at your code, I believe that you would want to move the else statement up a little bit.

Changing the code to accomodate this, you would get:

local part = script.Parent
local monkey = true
local coolDown = true
part.Touched:Connect(function(otherPart)
	local humanoid = otherPart.Parent:FindFirstChild("Humanoid")
	local RootPart = otherPart.Parent:FindFirstChild("HumanoidRootPart")
	
	if humanoid then 
		if coolDown == true then
			if monkey == true then
				monkey = false
				coolDown = false
				RootPart.Position = RootPart.Position + Vector3.new(0, 0, 10)
				
				wait(1)
				coolDown = true
			else
				monkey = true
				coolDown = false
				RootPart.Position = RootPart.Position + Vector3.new(0, 0, -10)
			
				wait(1)
				coolDown = true
			end
		end
	end
end)
2 Likes

Thank you! It worked! I had to do a lot of messing around because after I moved the else statement it kept on teleporting me a bit too much, but then I realized that I didn’t have a cooldown on the else statement. But anyways, thanks a lot and thanks for the explanation too!