Hope I’m not being stupid here… can’t find what I need in the docs.
How do I iterate through objects in a scene? I want to build a maze using prefabs in the editor, then place empty ‘nodes’ at each square of the maze (think the dot positions in Pac-Man) which the movement script will use to tell the character if he can go in a particular direction. I want to cycle through all nodes in a scene, and check their position. These nodes will either be children of each maze section prefab, or alternatively I could have one separate object parenting all the nodes together.
It would be the equivalent of saying:
For each object called ‘node’ {
Check position
}
I’ve figured out how to do it with for (var node : Transform in nodes)
but that requires me to have my nodes separate to the maze prefabs, which is fine except that it’ll make building the levels more laborious. Ideally I’d like to include a node as a child of each prefab, then have the script find all of those different nodes even though they are children of different parents and not the ONLY children of those parents. Is that possible?
You could create a tag for the node objects and then use FindGameObjectsWithTag to get them all, regardless of their parents. However, if you need to cycle through the nodes in any particular order, you will need a naming convention for them (eg, “Node001”, “Node002”, etc). Another approach is to add a GameObject array to the script that processes the nodes and add the nodes in here in the correct order.
Tags, brilliant! I hadn’t looked into them before, that’s EXACTLY what I need. I don’t need to find them in any order, I can cycle through them and check their positions, much like in the documented example.