How do I loop through everything in an instance or model?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to achieve to retrieve the items named “Door”

  2. What is the issue? Include screenshots / videos if possible!
    I am unable to get them

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub? Tried everything I could, every FindFirstChild

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

function getProximityPrompts()
	for _, v in pairs(game.Workspace:GetChildren()) do
		print(v)
		--print(typeof(v))
		
		if v:FindFirstChild("Door") then
			return v
		end
		
	end
end

image

for _, v in pairs(workspace:GetDescendants()) do
	print(v)
	
	if v:FindFirstChild("Door") then
		return v
	end
end

This should maybe work…

1 Like

Have you tried GetDescendants?

Try looking for the ProximityPrompts itself first then return its parent. You should make a table to contain every single object instead of returning the first object found. return breaks off the function as it thinks it’s already finished with its job, well, at least that’s how I understand it. No intention to spread misinformation whatsoever.

function getProximityPrompts()
    local list = {}
    for _, v in pairs(workspace:GetDescendants()) do
    	if v:IsA("ProximityPrompt") then
            table.insert(list,v.Parent)
        end
    end
    return list
end

This should return a table full of objects that have ProximityPrompt in it.
Or if you only want objects with the name Door, you can do:

function getDoors()
    local list = {}
    for _, v in pairs(workspace:GetDescendants()) do
    	if v:IsA("ProximityPrompt") and v.Parent.Name == "Door" then
            table.insert(list,v.Parent)
        end
    end
    return list
end

This should return a list of every Door with a ProximityPrompt in it.

There may be many ProximityPrompts, so let’s avoid confusion by renaming the function to get doors only.

3 Likes

Thank you, also now I have come across another problem. Im using CollectionService Now.

image

Code:

function GetAllDoorsAndListen() 
	for _, door in pairs(CollectionService:GetTagged("Doors")) do
		print(door)
		if door:FindFirstChild("ProximityPrompt") then
			local prompt = door.ProximityPrompt
			prompt.Triggered:Connect(function(player)
				if isOpened then
					prompt.ActionText = "Close Door"
					openDoor(door)
					wait(2)
					isOpened = false
				else
					prompt.ActionText = "Open Door"
					closeDoor(door)
					wait(2)
					isOpened = true
					
				end
		
				
			end)
		else
			print(door)
		end
	end
end

But problem is, some doors might be different and I want to loop and when I get it, how do I get the original parent. The model/instance?

Nvm about this, I think I found a way to counter this.