Why isn't my raycast pointing in the lookvector position?

I need help with my script. It’s supposed to shoot a ray out of the front of the handle of a tool, but it wasn’t working.

Instead of my raycast shooting, I get an error: “Attempt to index nil with Instance”. Can someone please fix my script and explain why my script wasn’t working?

--Variables and properties
local RunService = game:GetService("RunService")

local RayOrigin = script.Parent.Position
local RayDirection = script.Parent.CFrame.LookVector * 50 --This is what I believe that is causing the problem.

local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {script.Parent}
rayParams.FilterType = Enum.RaycastFilterType.Blacklist

--Actual casting
local rayResult = workspace:Raycast(RayOrigin, RayDirection, rayParams)
local hitPart = rayResult.Instance

if hitPart.Parent == workspace then
	print("a ray hit the workspace's child")
end

So, to test what the problem was, I messed with the variables a little and I think I found the source of the problem. If I change the variable “RayDirection” in to something like Vector3.new(0,-100,0), then it works. That’s why I think it has to do with LookVector. I also found out that the problem was not caused due to the tool not being equipped because I did the tool equipped function as a test but I still got the error. Please help me with this.

2 Likes

[RaycastResult] Contains the results of a raycast operation, or nil if no eligible BasePart or Terrain cell was hit.

1 Like

So the problem is that it’s not detecting anything?

1 Like

Yep, you can resolve this using a nil check to prevent indexing nil variables like so below:

--Actual casting
local rayResult = workspace:Raycast(RayOrigin, RayDirection, rayParams)
--check if it hit anything in the first place
if rayResult then
local hitPart = rayResult.Instance

if hitPart.Parent == workspace then
	print("a ray hit the workspace's child")
end
end

I’m on mobile sorry for formatting.

3 Likes

The problem is that you’re not handling the return value appropriately.

1 Like

I tested it and it worked. Thank you.

1 Like