Attempting to check if raycast's hit returns a nil value

So im reposting this because I am the worst person when it comes to understanding how formatting on this forum works lol, I suck at code embedding on this site it looks like, I am attempting to create a tree positioning system, so far, its lit. The issue is, theres a line, elseif hit == nil, but it doesn’t run that even though it is returning nil, or do I suck at reading the output? Which one, the output does return attempt to index local hit (a nil value), but the code doesnt run

local maxY = 20.19 -- Put highest Y point in the world!
local minY = 3.875 -- Put lowest Y point in the world!
local maxZ = 303.875 -- Put highest Z point
local minZ = -833.375
local minX = -436.625
local maxX = 356.625

local cloneTree = game.StarterPack.Part:Clone() --Clone Part and declare it from the StarterPack
        print("Clone")
        cloneTree.Parent = workspace
cloneTree.Position = Vector3.new(math.random(minX, maxX), math.random(minY, maxY), math.random(minZ, maxZ))
        print("Positioned")
        
cloneTree.Anchored = true
            print("Anchored")
        cloneTree.Name = "spawned"
                math.randomseed(tick())
                    local ray = Ray.new(cloneTree.Position, Vector3.new(0,-3,0))
                            local hit,position = workspace:FindPartOnRayWithIgnoreList(ray, {cloneTree})
                                        repeat    
                                            wait()
                                    if hit.Color == Color3.fromRGB(75, 151, 75) then
                                                leveled = true
                                        print("Leveled!")
                                        
                                    elseif hit == nil then
                                        math.randomseed(tick())
                                                leveled = false
                                                    
                                        
    cloneTree.Position = Vector3.new(math.random(minX, maxX), math.random(minY, maxY), math.random(minZ, maxZ))
                                            print("recloned")
                                    end
                                            print(leveled)
                                        until leveled == true```

if-statements are evaluated in order. You should put the nil check first.

EDIT: Also, you’re not raycasting again in the repeat-block. You’re going to encounter an infinite loop if hit is nil.

1 Like