There are several ways to get around problems like this, all in which have their appropriate time for different implementations. Here I'll go over several methods and example for each one, and I'll let you decide which seems more suitable for your situation.
Using different names
Yes, I know. This doesn't solve the core problem at all. However, what you name something is very important. You should chose names carefully and appropriately to make things easier to both visualize, and code.
Storing objects differently
Sometimes you can get around problems like this if you have a very specific location for each one of your objects.
Remember, the problem is trying to find an object with the same name, in the same directory. Using different directories (objects that store whatever you're searching for), can allow you to hold objects with the same name, so long as the directory is different.
This method however, is not practical if you're going to be scanning a large array of objects, all in which have the same name. That pretty much brings you back to your initial problem, since each directory would need a different name to access it's descendants. Take this for example, you can access both the parts that have the same name individually, but in different directories.
Finally, iteration
If you have a considerable amount of objects all with the same name, serving the same purpose, a for loop is the guy for the job. All we're going to do, is simply collect all of the objects within a table using GetChildren, then iterate that table with the for loop. During this process, we'll connect a Touched event to each element inside the array as the loop cycles through. Here's an example:
local storage = game:GetService("ServerStorage")
local parts = storage:GetChildren()
for i = 1, #parts do
local part = parts[i]
if part:IsA("BasePart") then
part.Touched:connect(function(hit)
print("Part was touched")
end)
end
end
That sample code will connect a Touched event to all parts collected in the ServerStorage service. If you have any questions, or if anything was unclear, just let me know!
1 comment
Is there a way for it to check for name instead of the type of part it is on line 16?