Prevent NIL RaycastResult from BreakingScript

How do I prevent a Nil RaycastResult value from affecting my other scripts? This problem occasionally appears and breaks my script, I tried using If RaycastResult == nil then return but this did not fix the issue.

Additional info: My other code below relies on the result of the Raycast Code above in order to function. Not too sure if this is just bad scripting or lacking in code management.

Error: attempt to index nil with ‘Position’

Script:

local Point = tool.Handle.Point
		local PointLookVector  = Point.CFrame.LookVector
		
		local RaycastParams = RaycastParams.new()
		RaycastParams.FilterDescendantsInstances = {tool.Parent}
		RaycastParams.FilterType = Enum.RaycastFilterType.Exclude

		print(RaycastParams.FilterDescendantsInstances)
		local Point = tool.Handle.Point
		local doDmgRE = tool:WaitForChild("DoDamage")

		local RaycastResult = workspace:Raycast(Point.Position, PointLookVector * 500, RaycastParams)
		
		
		local RayPosition = RaycastResult.Position


	if RaycastResult == nil then 
				print("Jammed")
				
			else

Put if RaycastResult == nil before trying to access RaycastResult.Position.

if RaycastResult == nil then
print("Jammed") 
else 
local RayPosition = RaycastResult.Position
end
1 Like

Oh YEAH! My brain really is jammed up now…I kept thinking the issue was below RaycastResult. My bad, but thanks man!

To be fair, I was a much bigger fan of Roblox old raycast because it always returned something.

Being someone who’s worked with other programming languages as well, having a function return nil or null is usually dangerous or risky if not handled properly.

I just rewrite Roblox raycasts or put them in a module script that wraps them up in a safe function call so it never has to return nil.

Sometimes I just like to return a dummy value instead that I can check so I know for certain that the raycast didn’t hit anything and it won’t break scripts that aren’t expecting a nil value.

2 Likes

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