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
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.