Introducción
Bienvenida al curso
Introducción a los Scripts en Unity: Ciclo de vida y métodos
OnDisable, OnDestroy, OnMouseDown
Usando la consola de una forma muy pro
Propiedades públicas y privadas, [SerializeField], [Header] y [HideInInspector]
Clases serializables
Causar cambios
El componente transform y los vectores
Manipulando al componente Transform
Manipulando al componente Transform: rotación y escala
Manipulando al componente Transform: vectores direccionales
Interpolaciones
Tiempo
Tiempo en Unity
Contando el tiempo: tiempo total y tiempo delta
Movimiento y tiempo
Creando movimiento independiente del framerate
Interacción
GameObjects que responden a su entorno
Leyendo al jugador (teclado)
Leyendo al jugador (teclado y gamepad)
Comunicación
Encontrando componentes
Hijos y padres
Comunicación telepática: eventos
Arquitectura
Inicializando variables
Configuración, Información e Inicialización
Cierre
Despedida del curso
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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.
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.
To interact with the children GameObjects of a parent object, there are multiple practical methods and equivalent to operations with Arrays:
Access by index: use transform.GetChild(index)
to access a specific child assigned to an index, starting from 0.
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);}
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")
.
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:
Initialize the level index: create a currentLevel
variable that indicates the current level the player is in.
public int currentLevel = 0;
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; } }} }
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);
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.
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
Want to see more contributions, questions and answers from the community?