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

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

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

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)

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