Question about understanding some tutorial code and transform.parent
Hey guys, this is my first post so sorry if the formatting looks crappy or I posted in the wrong place!
So I'm doing a tutorial and so far I follow pretty well, but there's one bit I don't understand:
void Start ()
{
foreach (Transform child in transform)
{
GameObject enemy = Instantiate (enemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
enemy.transform.parent = child;
}
}
I understand that (Transform child in transform) is saying "for each transform that is a child of the parent transform" do this. I also understand that it's creating an enemy on each one. The last line is what confuses me.
"enemy.transform.parent = child;"
I'm not sure what this is doing or even why it's there. To me, it looks like it's saying "set the parent transform to be.. a child?" I'm don't quite get it and it's really bothering me as I obviously like to understand what the tutorial is doing as opposed to just following step by step instructions.
Answer by Incognito357 · Feb 29, 2016 at 01:25 AM
It looks to me that this line is setting the parent of the newly instantiated enemy object to the current transform the for loop is iterating over. Essentially, this code loops through all the children of the object this script is attached to, and creates an enemy as a child of each of those transforms. The 'child' object (the object from the for loop iteration)'s parent is the object this script is attached to, and the enemy's parent is set to 'child'. This makes the enemy the 'child' object's child.