I am trying to get parts inside a region with :FindPartsInRegion3WithWhiteList().
The whitelist I set up has some parts inside it. These parts have other parts as children.
Is it possible to ignore descendants of an instance, so that the part I add is the only one that shows in the detection, instead of the part I added and its children?
Weird method, but do repetitive recursion upwards until the parent is not a BasePart, then add that to an array. Repeat this process for all parts returned in the array from FindPartsInRegion3WithWhiteList until the array has been exhausted, then run a function across all the items in the array.
local regionParts = PLACEHOLDER:FindPartsInRegion3WithWhiteList(ARGUMENTS)
local parts = table.create(#regionParts)
local recordedParts = table.create(#regionParts)
for _, part in ipairs(regionParts) do
local ancestorPart = part
-- While ancestorPart has a parent and it's a BasePart, look at its parent
while ancestorPart.Parent and ancestorPart.Parent:IsA("BasePart") do
ancestorPart = ancestorPart.Parent
end
if ancestorPart:IsA("BasePart") and not recordedParts[ancestorPart] then
table.insert(parts, ancestorPart)
recordedParts[ancestorPart] = true
end
end
for _, part in ipairs(parts) do
-- Insert functionality here
end
I am unaware of any edge cases this may present, as the array returned from FindPartsInRegion3WithWhiteList is explicitly comprised of parts. So here’s what the for loop does:
For every part returned in the table, we run a certain operation on them.
We set a tracker local variable, ancestorPart, to the part found in the table.
If this part has a parent and the parent is a BasePart, we move the ancestorPart up one to the parent BasePart. This continues until either the part doesn’t have a parent or the parent of the part is not a BasePart.
We confirm what we’ve found. Is the ancestorPart, after all this, still a BasePart? If yes, place it into a table. We also place it into a secondary table to prevent it from being inserted into the table again if another part shares that part as an ancestor.
Once our table has been filtered, we run operations on the collected parts array.
Some things to keep in mind:
This is an ugly solution. There is definitely a better way to do this. If there isn’t, then wow this is still a really ugly solution.
I do not clean up the recorded parts table, which could present a memory leak. Make sure to clean it up by dislodging all strong references and getting rid of the reference to the table.