Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why is this returning nil?

Asked by 9 years ago

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
1
Perhaps try print(hit.Name)? SlickPwner 534 — 9y
0
I got an error saying:Workspace.Script:7: attempt to index local 'hit' (a nil value) kevinnight45 550 — 9y

1 answer

Log in to vote
1
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

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
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 kevinnight45 550 — 9y
0
Workspace.Script:7: attempt to index local 'hit' (a nil value) kevinnight45 550 — 9y
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. adark 5487 — 9y
0
Are both 'hit' and 'position' nil? adark 5487 — 9y
0
I really don't know I copied half from a tutorial I found on Roblox Wiki called "Raycasting" kevinnight45 550 — 9y
Ad

Answer this question