Raycasting not working properly

local uis = game:GetService("UserInputService")
local lPlr = game.Players.LocalPlayer
local mouse = lPlr:GetMouse()
uis.InputBegan:Connect(function(input,epe)
	if epe then return end
	if input.KeyCode == Enum.KeyCode.E then
		local origin = lPlr.Character.Head.Position
		local direction = Vector3.new(mouse.Hit)
		
		local raycastParams = RaycastParams.new()
		raycastParams.FilterDescendantsInstances = {lPlr.Character.Head}
		raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
		local raycastResult = workspace:Raycast(origin, direction, raycastParams)
		
		local nPart = Instance.new("Part", workspace)
		nPart.Anchored = true
		nPart.Size = Vector3.new(5,5,5)
		nPart.Position = raycastResult.Position
	end
end)

I am trying to make a raycast, and when someone presses E, it creates a part where the raycast result’s position is, but I am currently failing at doing so.
Is there anything I’m doing wrong?
Here’s the error I get:

Players.DevAX1T.PlayerScripts.LocalScript:18: attempt to index nil with 'Position

Thanks,
DevAX1T

For your direction vector, maybe try…

local direction = (IPlr.Character.Head.Position - mouse.Hit.p).Unit * 10

I’m still getting the same error. I’m not sure why, but it’s being stubborn.

To clear things up:
raycastResult is nil for some reason(pretty sure, at least)

Try printing

print(raycastResult.Position)

If it prints “nil” then there you go, you have no raycastResult

i already tried “if not raycastresult”, and it didnt return anything so, its nil

Part, Position ,LookVector, Matterial = workspace:FindPartOnRay(Ray,ItemToIgnore, Water, Treat terrarin as cubes)
Redo your whole script and please use Ray.new(Position,LookVector)

Mk, but workspace:Raycast() works, even in game, according to this wiki post, so i’m quite stumped

WorldRoot | Documentation - Roblox Creator Hub It’s way easier to use findpartsonray

1 Like

mk, thanks! i’ll be sure to use this