"Attempt to index nil with instance" error on raycast

The raycast checks what part the player is climbing on when a player is climbing something and it keeps giving me this error for some reason, even though I’m using an if statement.

Code:

local plr = game.Players.LocalPlayer
local char = plr.Character
local hum = char:WaitForChild("Humanoid")

hum.StateChanged:Connect(function(_, new)
	if hum:GetState() ~= Enum.HumanoidStateType.Climbing then return end
	local root = char:FindFirstChild("HumanoidRootPart", true)

	local rayOrigin = root.Position
	local rayDirection = rayOrigin + root.CFrame.LookVector * Vector3.new(0, 0, 3)
	local raycastResult = game.Workspace:Raycast(rayOrigin, rayDirection)
	
	if not raycastResult.Instance then return end --This is the line giving the error!
	if raycastResult.Instance.Parent.Parent.Name ~= "Walljumpers" then return end
	game.Workspace.Gravity = 100
	wait(0.1)
	hum:SetStateEnabled(Enum.HumanoidStateType.Climbing, false)
	local connection
	local climbedPos = root.Position


	connection = hum:GetPropertyChangedSignal("MoveDirection"):Connect(function()
		if not (hum.MoveDirection.Magnitude > 0) and not ((climbedPos - root.Position).Magnitude >= 0.3) then return end
		connection:Disconnect()
		hum:SetStateEnabled(Enum.HumanoidStateType.Climbing, true)
		game.Workspace.Gravity = 150
	end)
		
	connection = hum.StateChanged:Connect(function()
		if hum:GetState() == Enum.HumanoidStateType.Landed then
			connection:Disconnect()
			
				
				
		end
	end)
end)
2 Likes

Try replacing it to:

if not raycastResult then return end

As far as I’m aware, if the raycast doesn’t find anything, the raycastResult itself will be nil, rather than the Instance.

1 Like

You’re checking if raycastResult.Instance exist. If raycastResult doesn’t exist, that means you’re checking if nil.Instance exist. Thus, the error, attempt to index nil with instance.

if rayResult then
  if rayResult.Instance then
  
  end
end

if rayResult and rayResult.Instance then end -- More concise, but doesn't let you execute code in case you have a ray but no instance

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