Find a random part that is of one material

I have a large driving game with lots of parts in it, and I wanted to create a wildfire system. To do this, I needed to find a random part to start. I know I could use GetDescendants and then choose a random number using the index, but I want the part chosen to be material Wood. Is there any function like “GetDescendantsOfType”?

Thanks!

You could do something along the lines of:

local workspace = game:GetService("Workspace")

for _, part: BasePart in ipairs(workspace:GetDescendants()) do
	if part.Material == Enum.Material.Wood then
		print("Part is wood")
	end
end

I have seen that before, but since my game has a lot of parts in it, it usually takes several minutes to loop through all of it. I want something a lot faster if possible.

You could use the collectionService by tagging wood type part

For example you could launch this in command bar:

for i, v in pairs(workspace:GetDescendants()) do
	if v:IsA("BasePart") and v.Material == Enum.Material.Wood then
		v:AddTag("wood")
	end
end

then in server scripts you could do this

local collectionService = game:GetService("CollectionService")
for _, part: BasePart in ipairs(collectionService:GetTagged("wood")) do
	print("Part has wood")
end

I will try this solution, and if it works, i’ll make yours the solution on the devforum. Thanks!

1 Like
local woodParts = {}

local function process(instance)
    if instance:IsA("BasePart") and instance.Material == Enum.Material.Wood then
        table.insert(woodParts, instance)
    end
end

-- Add all wood instances initially in workspace to the table
for _, instance in ipairs(workspace:GetDescendants()) do
    task.defer(process, instance)
end

-- When a new instance is added, add it to the table if needed
workspace.DescendantAdded:Connect(function(instance)
    task.defer(process, instance)
end)

-- TODO: Select a random instance from woodparts
-- If the selected part isn't in workspace, go through the table and remove all parts not in workspace, then try again

Sorry, I made an error:

Put this in the command Bar

for i, v in pairs(workspace:GetDescendants()) do
	if v:IsA("BasePart") and v.Material == Enum.Material.Wood then
		v:AddTag("wood")
	end
end

If you also want it with wood planks do this too:

for i, v in pairs(workspace:GetDescendants()) do
	if v:IsA("BasePart") then
		if v.Material == Enum.Material.Wood or v.Material == Enum.Material.WoodPlanks then
			v:AddTag("wood")
		end
		
	end
end