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

Help with 'for' loops, loops not looping properly?

Asked by 7 years ago

I'm making a ray casting gun with a :FindPartOnRayWithIgnoreList function and I want it to ignore objects that have CanCollide set to false.

Here is my code

local transparent
for i , v in pairs (workspace:GetChildren()) do
    wait()
    if v:IsA("Part") then
        if v.CanCollide == false then
            transparent = v
        end
    end
end

local part, pos = workspace:FindPartOnRayWithIgnoreList(ray{player.Character,transparent},false,false)

The problem is that the code only ignores one Non collide-able object. I want it to ignore all Non collide-able objects in the game.

1 answer

Log in to vote
0
Answered by
Azarth 3141 Moderation Voter Community Moderator
7 years ago
Edited 7 years ago

You'd need to run a recursive function (Calling a function in a function to repeat a process) to loop through the entirety of everything in Workspace and the objects Children.

local ignoreList = {player.Character}
local function recur(origin)
    for i,v in pairs(origin:GetChildren()) do 
        if v:IsA("BasePart") and v.CanCollide == false then 
            table.insert(ignoreList, #ignoreList + 1, v)
        end
        recur(v) -- Start another loop at v, which is the child of the last object.
    end
end

recur(Workspace) -- The root Object

local part, pos = workspace:FindPartOnRayWithIgnoreList(ray, ignoreList,false,false)

Ad

Answer this question