You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
1 Hrs
42 Min
37 Seg
Curso de Introducción a Unity: Scripting

Curso de Introducción a Unity: Scripting

Ruth Margarita García López

Ruth Margarita García López

Hijos y padres

20/24
Resources

How to handle hierarchies of GameObjects in Unity as Arrays?

One of the most common challenges in game development with Unity is the manipulation of Arrays or lists of elements. Often, it is required to group GameObjects and interact with them in an orderly and efficient way. In this session we will explore a different and exciting approach to handling hierarchies of GameObjects as an Array without the need to manually configure each element. This will eliminate common configuration errors and simplify the development process.

What is the child and parent structure?

In Unity, each GameObject exists in a visual and logical hierarchy. A GameObject can have several children, which in turn can have other sub-GameObjects. This forms a hierarchical structure where a parent object can contain multiple child objects.

  • Parent GameObject: Acts as a container that groups several entities.
  • Child GameObject: An element within a container that can be manipulated individually.

When handling these hierarchies, each child of a GameObject can be accessed similarly to an Array in programming, via indexes.

transform.GetChild(0); // Access the first child.

How do we access the GameObjects in the hierarchy?

To interact with the children GameObjects of a parent object, there are multiple practical methods and equivalent to operations with Arrays:

  1. Access by index: use transform.GetChild(index) to access a specific child assigned to an index, starting from 0.

  2. Traversal of all children: It is possible to iterate over all children using for loops, taking advantage of properties such as the number of children(transform.childCount). Here is a basic example of how to do it:

    for (int i = 0; i < transform.childCount;  i++) { Transform child = transform.GetChild(i); Debug.Log(child.name);}
  3. Access by name: Although it is less frequent and should be handled with care, it is possible to access a child by name using transform.Find("ChildName").

How to move between levels using the keyboard?

The goal when working with hierarchies is to facilitate navigation between objects, as if it were a level system in a game. Let's implement a system where a player can change levels using arrow keys:

  1. Initialize the level index: create a currentLevel variable that indicates the current level the player is in.

    public int currentLevel = 0;
  2. Detects user input: Monitors the user's arrow keys to move the player through the levels.

    void Update() { if (Input.GetKeyDown(KeyCode.RightArrow)){ if (currentLevel < transform.childCount - 1) {  currentLevel++; player.transform.position = transform.GetChild(currentLevel).position; } }} }
  3. Implements smooth movement: Although initially the player teleports, it is more attractive to achieve smooth movement between points. The lerp (interpolation) function is key to enhancing this experience:

    Vector3.MoveTowards(initialPosition, targetPosition, speed * Time.deltaTime);

How to improve the hierarchies for new levels?

Adding more levels or changing the order of existing ones is a matter of rearranging the child GameObjects in the hierarchy in Unity. This way, by duplicating and rearranging the GameObjects, our automatic navigation system will link these elements without additional errors, adapting the game flow to new requirements or creativity without changing a single line of code.

How can you improve the existing system?

I encourage you to extend the current functionality, how about also allowing the player to return levels with the left arrow key? Try to implement this feature and experiment with the tools provided by Unity and the hierarchy system as arrays.

Learning goes hand in hand with practice. If you have any questions or need more details, check out the supplementary material provided in the course resources. I'm here to help you and support your path in game development - go ahead, you're on the right track!

Contributions 1

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

![]()**Una breve explicación para entender la lógica** detrás de![]() ” currenteLevel < transform.childCount - 1)” usando terminos mas sencillos como currentLevel =nivel actual y Childcount =numero de niveles![]() ![](https://static.platzi.com/media/user_upload/niveles-7ea7810e-23f0-448a-8e71-bcfe7dc24c83.jpg) el personaje siempre podrá saltar al siguiente nivel,pero esto solo hasta el último nivel existente,donde la acción ya no será posible por que no existe otro nivel entonces: si nivel actual\<número de niveles se sumará 1 al nivel actual con lo que saltaremos al siguiente nivel si hacemos un prueba y estamos en el nivel 1![](https://static.platzi.com/media/user_upload/niveles1-fd07c18b-e7a9-4179-8437-5b9a8d616576.jpg) nivel actual (el nivel actual es 0) < numero de niveles(3 en este caso) 0<3 por lo que  será posible avanzar al siguiente nivel,el mismo caso al estar en el segundo nivel aún será posible avanzar al siguiente del mismo modo al estar en el siguiente nivel (nivel 1) la condicion aun se cumple nivel actual (el nivel actual es 1) < numero de niveles(3 en este caso) 1<3 Pero el problema surge al llegar al nivel 3![](https://static.platzi.com/media/user_upload/nivel%203%20dettenerse-8e67b35c-ec40-4df5-b82e-613e9d929641.jpg) nivel actual (el nivel actual es 2) < número de niveles(3 en este caso) 2<3 La condicion aun se cumple por lo que aun se podra avanzar al siguiente nivel,el cual no existe,y al avanzar a este inexistente  nivel  producirá un error![](https://static.platzi.com/media/user_upload/sguienteinexistente-2c52d26f-692e-4126-aeb3-b99117137f7f.jpg) el problema radica en que el conteo de unity comienza en 0 en lugar de 1,para poder cumplir la condición de manera correcta el número de niveles y el último nivel deben ser iguales para que ya no sea posible avanzar a otro nivel nivel actual < número de niveles -1 al estar en el nivel 0![](https://static.platzi.com/media/user_upload/niveles1-4df30cd9-5a55-4680-aca8-282f394eb77e.jpg) nivel actual (nivel 0)< número de niveles(3 en este caso) -1  0<3-1  0<2 aún es posible avanzar en este nivel, al igual que en siguiente nivel debería poderse pasar al siguiente nivel nivel 1  1<3-1 1<2 ahora probando en el último nivel donde la condición ya  no sería válida ![](https://static.platzi.com/media/user_upload/niveles3-2bb6670a-32a9-4bfc-bcb6-4b8c4c912a4e.jpg) 1<2-1 1<1 la condición ya no se cumple por lo que ya no será posible avanzar a un nivel inexistente, de esa manera llegamos al siguiente fragmento en el código currenteLevel < transform.childCount - 1 **Ahora pasaremos a la logica para poder retroceder un nive**l ![](https://static.platzi.com/media/user_upload/retroceso1-5b016176-fe00-42c7-9bd4-49c8a4112cf5.jpg) ![](https://static.platzi.com/media/user_upload/retroceso2-1244dea2-89c4-4c01-8e6b-5a58aeefaa12.jpg)siempre podremos avanzar al nivel anterior![](https://static.platzi.com/media/user_upload/retroceso3-aedfebf4-558f-4869-8d78-f31e70582482.jpg) siempre y cuando este no sea el primer nivel el cual por el conteo de unity siempre ser “0” por lo que podemos deducir que siempre que el nivel  actual sea mayor  al primer nivel(que siempre será cero) se podrá retroceder a un nivel anterior probando esta condición ![](https://static.platzi.com/media/user_upload/retroceso1-7ad27cd9-9ff7-47e1-8817-2ab319d03292.jpg) nivel actual >primer nivel(siempre será cero) 2>0 se cumple la condición y podemos retroceder el nivel ahora probando con el primer nivel (nivel 0)![](https://static.platzi.com/media/user_upload/retroceso3-0e2d0085-7475-4563-b311-da2f5b189108.jpg) nivel actual>0 0>0 la condición ya no se cumple por lo que ya no se podrá retroceder, por que tendremos el siguiente código dentro la condicional  (  currenteLevel >0)  que nos permitirá retroceder en lugar de ( currenteLevel < transform.childCount - 1) que nos permitía avanzar; el resto de código es prácticamente igual solo se deberá cambiar la tecla con la que se active en el teclado y en lugar de sumar un nivel se deberá restar un nivel