Placement Script: "attempt to index nil with 'Position'"

I want to achieve a fix for this error, the issue is that it always occurs when i put the mouse into the air and not onto another part, i can’t think of a solution myself as this placement script uses raycast and i am fairly new to it.

while IsBuilding do
	local UnitRay = Mouse.UnitRay
	local ray = Ray.new(UnitRay.Origin,UnitRay.Direction * 100000)
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	raycastParams.FilterDescendantsInstances = {Character,CurrentBlock}
	local RaycastResult = workspace:Raycast(ray.Origin,ray.Direction,raycastParams)

	CurrentBlockCFrame = CFrame.new(math.floor(RaycastResult.Position.X/GridSize) * GridSize,RaycastResult.Position.Y + CurrentBlock.PrimaryPart.Size.Y/2,math.floor(RaycastResult.Position.Z/GridSize) * GridSize)
	AnimCFrame = CurrentBlock.PrimaryPart.CFrame:Lerp(CurrentBlockCFrame,1/1.5)
	CurrentBlock:SetPrimaryPartCFrame(AnimCFrame)
						
	RunService.RenderStepped:Wait()
end

Try

while IsBuilding do
	local UnitRay = Mouse.UnitRay
	local ray = Ray.new(UnitRay.Origin,UnitRay.Direction * 100000)
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	raycastParams.FilterDescendantsInstances = {Character,CurrentBlock}
	local RaycastResult = workspace:Raycast(ray.Origin,ray.Direction,raycastParams)
	
	if RaycastResult then
		CurrentBlockCFrame = CFrame.new(math.floor(RaycastResult.Position.X/GridSize) * GridSize,RaycastResult.Position.Y + CurrentBlock.PrimaryPart.Size.Y/2,math.floor(RaycastResult.Position.Z/GridSize) * GridSize)
		AnimCFrame = CurrentBlock.PrimaryPart.CFrame:Lerp(CurrentBlockCFrame,1/1.5)
		CurrentBlock:SetPrimaryPartCFrame(AnimCFrame)
	end
						
	RunService.RenderStepped:Wait()
end

The code for moving the thing will only work if it has a RaycastResult, which I think it wont if you’re moving your mouse in the air

1 Like