Creating a hierarchical HUD in Unity

Español

 

UnityGameProject

I have been “playing” a bit with Unity for the last few months, building a very simple game (which the image at the top of this post belongs to) that I expect to release soon, and I have learned quite a few things about Unity. In this case I want to share my experience setting up hierarchical HUDs.

There are a bunch of great official tutorials on creating user interfaces (UI) in Unity, which are quite useful to learn about this functionality provided by Unity. But… what do I mean by “hierarchical HUDs”?

As you probably know, a HUD is basically the set of indicators a game shows in the display to give some information to the player. In the game I am creating, I found myself creating a HUD composed by several text objects: Score and Remaining Time. But sometimes, I needed to handle all of them as a single object. For example, when fading them in and out (because I have animated them to show and hide with a smooth animation). If they are independent, we have to create a separate animation for each of them, and handle each of them separately as well from our scripts.

The solution is to create a hierarchy with our HUD elements.

 

First step: create a UI hierarchy using an additional GameObject

HierarchicalHUD

A hierarchy in UI elements in Unity works very much as every game object hierarchy: we can create an empty GameObject in our Canvas (which I have named HUD in this case), and then drag all of the components inside of it. Very simple. BUT…

The fact that UI elements have sizes and positions relative to the screen (or, more precisely, relative to their parent object) forces us to make some adjustments so the components of the HUD keep working correctly on all screen resolutions.

 

Second step: make the container object match the Canvas

When we have just created our empty HUD game object, it appears as a square centered inside the Canvas:

CanvasGameObject

It has a fixed size. Given all HUD components will size and position relative to their parent object (the HUD object), we need the HUD object to adjust to the Canvas so it keeps being relative to the screen dimensions (otherwise, all HUD components will have fixed size and positions as well).

For this, we have to set the HUD to stretch to completely match its parent, so we select the HUD object and go to the Inspector, and set this configuration:

HUDObjectRectTransform

(when selecting the Stretch configuration, if we hold Alt while clicking on the stretch option, the dimensions will be automatically adjusted for us; otherwise we will have to manually set all values -Left, Top, Right, Bottom- to 0).

 

Third step: fix HUD components’ positions and sizes

After this, HUD components’ positions will probably be incorrect. We only need to configure their positions, sizes and anchor presets again and then we will have our hierarchical HUD working.

Now, it will be possible to activate or deactivate the whole HUD at once, or animate all of its components with a single animation and animation controller, or to store it as a prefab and instantiating it with a single line of code. For me, this has been quite useful. Hope it helps you too 🙂

 

Comment/share

 

==============

 

Creando un HUD jerárquico en Unity

 

UnityGameProject

He estado “jugando” un poco con Unity durante los últimos meses, construyendo un juego muy simple (al que pertenece la imagen de cabecera de este post) que espero publicar pronto, y he aprendido bastantes cosas sobre Unity. En este caso, quiero compartir mi experiencia configurando HUDs jerárquicos.

Hay un puñado de tutoriales oficiales geniales sobre crear interfaces de usuario (UI) en Unity, que son muy útiles para aprender sobre esta funcionalidad proporcionada por Unity. Pero… ¿a qué me refiero con “HUDs jerárquicos”?

Como probablemente sabéis, un HUD es básicamente el conjunto de indicadores que un juego muestra en pantalla para dar información al jugador. En el juego que estoy creando, me encontré creando un HUD compuesto por varios objetos de texto: Score y Remaining Time. Pero a veces, necesitaba manejarlos todos como un único objeto. Por ejemplo, al hacerlos aparecer y desaparecer con suavidad (porque los he animado para mostrarse y ocultarse con una animación suave). Si son independientes, tenemos que crear una animación separada para cada uno de ellos, y manejarlos también por separado desde nuestros scripts.

La solución es crear una jerarquía con los elementos de nuestro HUD.

 

Primer paso: crear una jerarquía de UI usando un GameObject adicional

HierarchicalHUD

Una jerarquía en elementos de UI en Unity funciona como cualquier jerarquía de objetos: podemos crear un GameObject vacío en nuestro Canvas (que yo he nombrado HUD en este caso), y entonces arrastrar todos los componentes a su interior. Muy simple. PERO…

El hecho de que los elementos de UI tengan tamaños y posiciones relativos a la pantalla (o, para ser más precisos, relativos a su objeto padre) nos fuerza a hacer algunos ajustes para que los componentes del HUD sigan funcionando correctamente en todas las resoluciones de pantalla.

 

Segundo paso: hacer que el objeto contenedor coincida con el Canvas

Cuando creamos nuestro objeto HUD vacío, aparece como un cuadrado centrado dentro del Canvas:

CanvasGameObject

Tiene un tamaño fijo. Dado que todos los componentes del HUD se escalarán y situarán relativos a su objeto padre (el objeto HUD), necesitamos que el objeto HUD se ajuste al Canvas de manera que siga siendo relativo a las dimensiones de pantalla (de lo contrario, todos los componentes del HUD tendrán también posiciones y tamaños fijos).

Para esto, tenemos que configurar el HUD para estirarse (stretch) hasta coincidir completamente con su padre, así que seleccionamos el objeto HUD y vamos al Inspector, para poner esta configuración:

HUDObjectRectTransform

(al seleccionar la configuración de Stretch, si mantenemos pulsado Alt mientras hacemos clic en la opción de stretch, las dimensiones se ajustarán automáticamente para nosotros; si no, tendremos que establecer manualmente todos los valores -Left, Top, Right, Bottom- a 0).

 

Tercer paso: arreglar posiciones y tamaños de los componentes del HUD

Tras esto, las posiciones de los componentes del HUD serán probablemente incorrectas. Sólo necesitamos configurar sus posiciones, tamaños y anchor presets de nuevo y tendremos nuestro HUD jerárquico funcionando.

Ahora, será posible activar o desactivar el HUD completo con una única acción, o animar todos sus componentes con un solo animation controller, o almacenarlo como un prefab e instanciarlo con una única línea de código. Para mí, esto ha sido muy útil. Espero que os ayude a vosotros también 🙂