Scripting Child Objects Through Parent

Can someone give me a few C# code examples on the ways to interact with child objects. I don’t know how to select specific ones through script, that is mainly what I want to know. Basically I have a spawn socket prefab of child objects and I need to know how to script to children objects, through the parent.

I have a prefab with children game objects laid out in space. It is a formation. I want my instantiated fighters and Dropships to find an empty slot on one of the prefabs spawn sockets (child) then go hover over it and it then say that it is full and the next fighters go to the next free slot till the formation is full. when its full a new formation will randomly spawn in another place, and the same thing will happen. Eventually they will move towards the player and attack.

Ok my null reference error is solved by another question. Basically I want the mothership to spawn the enemies, then have them look for a empty slot and physically move into position, not just instantly spawn into it. Because once one formation is full another will be created and more fighters will fill up the next formation and so on. But what I’m having problems with is I’m using a bool in my formation script to check if a slot is full or not, another script to check for a collision on one of the slots, if there is a collision Formation_AI.isEmptySlot = false; It should be false and the fighters go to the next slot with the other ifs, but its not turning false for some reason, I checked with debug and its staying true in the formation_AI, but I put debug in the collision script and it says false in that script but its not changing the formation script to false.

You can get any child directly with the function Transform.GetChild(zeroBasedIndex), or find it by name with Transform.Find(objectName):

var child1: Transform = transform.GetChild(1);

or

var child1: Transform = transform.Find("Child1");

GetChild was removed from the docs due to some unexplained reason, but it’s active and is used internally by Unity. Unfortunately, using it may be tricky when children are inserted or deleted, because the indexes of other children may be changed. Find(name) is slower, but doesn’t have this index issue (provided that you give a different name to each child, of course).

Another alternative (although not suitable in this case, I presume) is to use foreach (C#) or for…in (JS) to iterate through all children. This is fast and simple, but you don’t get the child index - just its Transform:

var n: int = 0;
for (var child: Transform in transform){
  // assign a sequential number to the variable childNum
  // in the script SomeScript in each children:
  child.GetComponent(SomeScript).childNum = ++n;
}