How to make a random part change to the specific material, color and transparency?

Basically a random part selected changes material, color and transparency, tried looking some of the tutorials, nothing seen so far.
I really do want to make some fantasy game that will work pretty well

If you want to pick a random part from the whole workspace:

local wspace = workspace:GetDescendants()

local parts = {}

for _, v in ipairs(wspace) do
    if v:IsA("BasePart") then
        table.insert(parts, v)
    end
end

local part = parts[math.random(1, #parts)]

-- set what you want
part.Color = Color3.fromRGB(0, 0, 0) 
part.Transparency = 0
part.Material = Enum.Material.Plastic
1 Like

There’s errors on line 7 and if you loop it, it will almost crash the game until the script automatically stops

Put the Part you want to have their Material, color and transparency changed In a folder

local Folder = script.Parent:GetChildren()


while true do
 local Part = math.random(1,#Folder)
If Part;IsA(“Part”) then
Part.Color = Color3.fromRGB(0,0,0)
Part.Transparency = 0
Part.Material = Enum.Material.Plastic
break
else
wait()
end

Make sure that the script is also inside the folder

2 Likes

I wrote the parameters wrong, now I fixed it and you can try again

local randomObject = Random.new(os.clock())
local baseParts = {}

local function randomizeBasePart(basePart : BasePart)
	basePart.BrickColor = BrickColor.Random()
	local randomIndex = randomObject:NextInteger(1, #Enum.Material:GetEnumItems())
	for materialEnumIndex, materialEnumItem in ipairs(Enum.Material:GetEnumItems()) do
		if randomIndex == materialEnumIndex then
			basePart.Material = materialEnumItem
		end
	end
end

local function getRandomBasePart()
	return baseParts[randomObject:NextInteger(1, #baseParts)]
end

local function getBaseParts()
	for _, descendant in ipairs(workspace:GetDescendants()) do
		if descendant:IsA("BasePart") then
			table.insert(baseParts, descendant)
		end
	end
end

local function onWorkspaceDescendantAdded(descendant)
	if descendant:IsA("BasePart") then
		local basePartIndex = table.find(baseParts, descendant)
		if not basePartIndex then
			table.insert(baseParts, descendant)
		end
	end
end

local function onWorkspaceDescendantRemoving(descendant)
	if descendant:IsA("BasePart") then
		local basePartIndex = table.find(baseParts, descendant)
		if basePartIndex then
			table.remove(baseParts, basePartIndex)
		end
	end
end

workspace.DescendantAdded:Connect(onWorkspaceDescendantAdded)
workspace.DescendantRemoving:Connect(onWorkspaceDescendantRemoving)
getBaseParts()
local basePart = getRandomBasePart()
randomizeBasePart(basePart)

I didn’t implement random transparency but you should be able to handle that.

1 Like