Attempt to index nil with instance

I’ve made a function that gets a target from the users mouse location, however the code breaks if my mouse is pointing at the sky. How can i fix that?

Code:

local function getTarget()
	local pos = UserInputService:GetMouseLocation()
	raycastParams.CollisionGroup = "Characters"
	local Ray = workspace:Raycast(game.Workspace.CurrentCamera.CFrame.p, game.Workspace.CurrentCamera:ViewportPointToRay(pos.x, pos.y, 0).Direction * 1000, raycastParams)
	
	if Ray.Instance then
		return Ray.Instance
	end

	
	return nil
end

Is the error in here? I think the error would be wherever the instance returned is used.

1 Like

The code errors at the line

   If Ray.Instance then

I fixed it by changing the code to this:

  local function getTarget()
	local pos = UserInputService:GetMouseLocation()
	raycastParams.CollisionGroup = "Characters"
	local Ray = workspace:Raycast(game.Workspace.CurrentCamera.CFrame.p, game.Workspace.CurrentCamera:ViewportPointToRay(pos.x, pos.y, 0).Direction * 1000, raycastParams)
	
	if Ray then
		return Ray.Instance
	end

	
	return nil
end

you can single-line this:

return (Ray and Ray.Instance) or nil
1 Like

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