Attempt to index nil with 'Distance'

Hello,

I am making a move where the player throws a magma ball; This works with my current script but after a few usages of the move, it breaks and gives me the error “Attempt to index nil with ‘Distance’”.
Here’s the Module Script:

local Moves = {}

function Moves.magmaBall(ball,TITime,humanoidRootPart)
	ball.CFrame = humanoidRootPart.CFrame
	local raycastparams = RaycastParams.new()
	raycastparams.FilterType = Enum.RaycastFilterType.Blacklist
	local raycast = workspace:Raycast(humanoidRootPart.Position,humanoidRootPart.Position + Vector3.new(0,100,0),raycastparams)
	local goals = {["Position"] = raycast.Distance*raycast.Normal} -- error line
	local tweenService = game:GetService("TweenService")
	local TI = TweenInfo.new(TITime)
	local track = tweenService:Create(ball,TI,goals)
	track:Play()
	track.Completed:Connect(function()
		ball:Destroy()
	end)
end
return Moves

I am grateful for any type of help in this situation!

1 Like

You shouldn’t make duplicates

Your raycast returns nil if it doesn’t hit anything.

Ok, what should I do to handle the error??

	local raycast = workspace:Raycast(humanoidRootPart.Position,humanoidRootPart.Position + Vector3.new(0,100,0),raycastparams)
if raycast then
--your code here
end

Alright, that seemed to handle the error. Thank you.

1 Like

Another question, how do I always make the raycast hit an object?

you can’t really do that, because there’s always a chance it hits nothing (like shooting at the sky, or the ray is too short to hit an object)

it’s a lot safer to have a condition to check if it hit something

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