Child.transform.position should be child.position as child is a transform

The lecture uses child.transform.position for the new enemies. That seems to work but is really not correct as the child is a transform, so it is ok to specify child.position as position:

foreach (Transform child in transform) {
	var enemy = (GameObject)Instantiate(enemyPrefab, child.position, Quaternion.identity);
	enemy.transform.parent = child;
}
2 Likes

Agreed, it works, but does anyone know why child.transform.position also works?

In fact child.transform.transform.transform.position works too! :confused:

Is the compiler just auto-correcting it without generating an error or warning, or what?

If you look at the documentation for Transform, it’s derived from the Component class. The component class has a field named transform, which contains “the Transform attached to this GameObject”. So it looks like, the Transform class always has a reference to its own transform, which is why transform.transform.transform.transform... works.

If you’re new to object-oriented programming (C# is an object-oriented language), I encourage you to read more about Inheritance, one of the most important features of object-oriented languages.

Privacy & Terms