Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is this returning nil?

I'm trying to print the name of part that is raycast too,but it prints nil. Why does it print nil and how do I fix it?

How I have it setup The red part is Part1 The green part is named Part

while wait()do
local Ray = Ray.new(game.Workspace.Part1.Position,--the ray will start at this part
game.Workspace.Part1.CFrame.lookVector.unit)--Ray will come out of the front

local hit,position = Workspace:FindPartOnRay(Ray,_)

print(hit)--print name of thing that the ray hit
end

For adark

while wait()do
    local Ray = Ray.new(game.Workspace.Part1.Position,
    game.Workspace.Part1.CFrame.lookVector.unit*10) -- 1000 is normally used, but you can reduce as you see fit. Not multiplying this is only 1 stud from Part1's *center* towards its lookVector.

    local hit = Workspace:FindPartOnRay(Ray)

    if hit:IsA("Part") then
	game.Workspace.Part1.BrickColor = BrickColor.new("Bright green")
else
	game.Workspace.Part1.BrickColor = BrickColor.new("Bright red")
end
end

2 comments

1

Perhaps try print(hit.Name)?

0

I got an error saying:Workspace.Script:7: attempt to index local 'hit' (a nil value)

1 answer

✓ Accepted answer

This is returning nil because the length of the Ray created is 1 stud, so even if the lookVector of the red brick is directly aiming at one of the green bricks, it won't go far enough to reach it.

To fix this, multiply the second argument given to the Ray.new() constructor by some amount:


while wait()do
	local Ray = Ray.new(game.Workspace.Part1.Position,
	game.Workspace.Part1.CFrame.lookVector.unit*1000) -- 1000 is normally used, but you can reduce as you see fit. Not multiplying this is only 1 stud from Part1's *center* towards its lookVector.
	
	local hit,position = Workspace:FindPartOnRay(Ray,_)
	
	print(hit)--print name of thing that the ray hit
end

5 comments

0

I have another question how will I change a color of part that touches the ray?I tried it but I got a error

0

Workspace.Script:7: attempt to index local 'hit' (a nil value)

0

I'd also like to point out that the "Ray, " you used inside the FindPartOnRay is unnecessary and dangerous: only use '' to catch unwanted returned values, never as an argument, unless you know exactly what it contains.

0

Are both 'hit' and 'position' nil?

0

I really don't know I copied half from a tutorial I found on Roblox Wiki called "Raycasting"

This discussion is preserved as it was. New answers, comments, and votes are closed.