Detecting multiple parts with the same name?

Basically - I’m attempting to script a tycoon from scratch. Currently I’m trying to figure out how to avoid placing a script in each button by using one universal script that handles all purchases within the tycoon.

My initial solution was to loop through a folder containing all the button models via a “for” loop, finding any BasePart with the name “Button”, and assigning it to a local, like so:

local button
for _, descendant in pairs(buttonsFolder:GetDescendants()) do
	if descendant:IsA("BasePart") and descendant.Name == "Button" then
		button = descendant
	end
end

In hindsight, it wasn’t exactly the brightest way of going about this. I probably should’ve expected it’ll only assign one descendant to the “button” local.

Would I be able to use a table instead, and how would I be able to call the buttons within the table later in a Touched function? Alternatively, would I be better off putting multiple scripts into the individual buttons, and if I am, what effect would that have on a full, running server? [ The game has eight available tycoons and I’m sure the effects would stack up after a while. ]

1 Like

Hey! I believe what you’re looking for actually does not need a variable outside of the for loop. You could actually just call the .Touched event inside of the if statement for each button like so:

for _, descendant in pairs(buttonsFolder:GetDescendants()) do
	if descendant:IsA("BasePart") and descendant.Name == "Button" then
		descendant.Touched:Connect(function(part)
			--player is trying to purchase item
		end)
	end
end

Inside of the .Touched function I’d validate the part touching is a player character and that obviously only the tycoon owner can purchase the item

7 Likes

Ahh yup, that did the trick! I was initially weary to place a function inside a loop but it runs perfectly fine so far. Thank you!

1 Like