Attempt to index nil with 'Position'

Hello. I was trying to make a system where it would send a raycast from your camera, to your mouse. However, I keep getting this error, and I don’t know what is wrong.

attempt to index nil with 'Position'

Here is the localscript:

local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()
local camera = workspace.CurrentCamera

local function spawnDummy()
	local camPos = camera.CFrame.Position
	local mousePos = mouse.Hit.Position
	local raycast = workspace:Raycast(camPos,mousePos)
	print(raycast.Position)
	local dummy = game:GetService("ReplicatedStorage"):WaitForChild("Rig"):Clone()
	dummy.HumanoidRootPart.Position = raycast.Position
	dummy.Parent = workspace
end

mouse.Button1Down:Connect(spawnDummy)

Thanks for the help!

What line is the “attempt to index nil with 'Position” error on?

It is the line with the print command.

WorldRoot:Raycast() returns nil if the Raycast didn’t hit anything

Oh my god I can’t believe I didn’t see the raycast function, yea it’ll return nil if it didn’t hit something.

So make sure you do

if raycast then
--- Rest of the code here
end

Yeah, but the raycast does not hit anything still.

if you want to get the position where the mouse hits to place a dummy there you can just use mouse.Hit

That’s what I originally did, but for what I’m doing, it has to be a raycast.

1 Like

Multiply the mouse hit by 1000, the direction is too short so it is returning nil.

Good idea, but it still didn’t work.

use this

local function VisualizeRaycast(origin, direction)
	local midpoint = origin + direction*0.5;
	
	local part = Instance.new("Part");
	part.Anchored = true;
	part.CanCollide = false;
	part.Name = "DebugPart";
	
	part.CFrame = CFrame.lookAt(midpoint, origin);
	part.Size = Vector3.new(0.1, 0.1, direction.Magnitude);
	
	part.Material = Enum.Material.Neon;
	part.BrickColor = BrickColor.Red();
	
	part.Parent = workspace.Exclude;
end;

go from the origin to the mousehitposition(direction) * 1000

Also make sure part.Parent is workspace instead of workspace.Exclude. This was a function for debugging my raycasts.

i use this function in my game, idk if its what your looking for

local GetMouse3DPosition = function()
	local unitRay = Camera:ScreenPointToRay(Mouse.X, Mouse.Y)
	local raycastResult = workspace:Raycast(unitRay.Origin, unitRay.Direction * 10000)
	if raycastResult then
		return raycastResult.Position
	else
		return nil
	end
end
2 Likes

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