Trying to raycast from the players position, and it doesn't work

I’ve never really grasped raycasting fully, but I tried to do this, and it doesn’t work for some reason. It’s super weird, cause if i look in a ceritan direction, i get the error “Players.Dogemeowbarf.PlayerGui.ScreenGui.LocalScript:27: attempt to index nil with ‘Instance’
And if I look in another direction, It just gives me the baseplate, which is not what I want, cause i’m trying to raycast in the position of the players HumanoidRootPart. But yeah, please tell me what i’m doing wrong here.

local players = game:GetService("Players")
local uis = game:GetService("UserInputService")

local gui = script.Parent
local player = players.LocalPlayer
local character = player.Character
local hrp = character:FindFirstChild("HumanoidRootPart")
local torso = character:FindFirstChild("Torso")
local head = character:FindFirstChild("Head")

local params = RaycastParams.new()
params.FilterDescendantsInstances = {character}

local function raycast()
	local raycastResult = workspace:Raycast(hrp.Position, hrp.Rotation, params, 100000)
	return raycastResult
end

local debounce = false
local debounceTime = 1

uis.InputBegan:Connect(function(inpObj, gpe)
	if gpe then return end
	if debounce == true then return end
	if gui.Enabled == true then
		if inpObj.KeyCode == Enum.KeyCode.R then
			print(raycast().Instance)
		end
	end

end)

In line 27, its correct, but when you raycast and the ray hits nothing, it Will return nil. So you could add an check “if raycast and raycast.Instance then”

This is some great info, but my problem still isn’t solved. See, whenever I look to a certain direction, it doesn’t print the thing, and also It’s printing the baseplate when i’m trying to raycast forward from the torso.

In your raycast function, you use hrp.Rotation as the direction. Rotation is not the same as the direction the part is facing. In that cast, you’d want to use hrp.CFrame.LookVector

The reason you’re getting the error “attempt to index nil with ‘Instance’” is because you’re calling print(raycast().Instance) without verifying that raycast() actually returned a result.

Also, I’m not sure what the extra number you’re using after params is. If that’s the length of the ray, multiply Direction * Length, so you’d replace hrp.Rotation with hrp.CFrame.LookVector * 100000, but that’s a bit overkill as the maximum Ray length is 15,000 studs.

1 Like