Guía Completa de Implementación: Sistema FlexBox y FlexGraphic para Unity
📋 Información del Documento
Versión: 2.0 | Compatibilidad: Unity 2022.3 LTS+ | Fecha: Septiembre 2024
Esta guía te enseñará paso a paso cómo implementar y usar el sistema FlexBox y FlexGraphic en Unity, desde la configuración inicial hasta casos de uso avanzados.
🌙 Nuevas características: Soporte para tema oscuro y claro, navegación mejorada y diseño responsivo.
🚀 Introducción al Sistema
¿Qué es FlexBox y FlexGraphic?
El sistema FlexBox y FlexGraphic es una implementación completa de CSS Flexbox para Unity UI que permite crear layouts flexibles y responsivos de manera intuitiva.
✨ Ventajas del Sistema
- ✅ Layouts responsivos automáticos
- ✅ Alineación precisa sin cálculos manuales
- ✅ Espaciado consistente entre elementos
- ✅ Soporte completo para diferentes tamaños de pantalla
- ✅ Integración nativa con el sistema de Layout de Unity
- ✅ Componentes gráficos avanzados con esquinas redondeadas
⚙️ Configuración Inicial
Paso 1: Verificar la Estructura del Proyecto
Asegúrate de que tu proyecto tenga la siguiente estructura:
Assets/
├── FlexUI/
│ ├── FlexBox/
│ │ ├── FlexBox.cs
│ │ ├── FlexElement.cs
│ │ ├── FlexEnums.cs
│ │ ├── FlexLayout.cs
│ │ ├── FlexLayoutCalculator.cs
│ │ ├── FlexPositioner.cs
│ │ ├── FlexSizeCalculator.cs
│ │ ├── FlexUtility.cs
│ │ ├── FlexChildrenManager.cs
│ │ ├── IFlexContainer.cs
│ │ ├── IFlexItem.cs
│ │ └── Editor/
│ │ ├── FlexBoxEditor.cs
│ │ ├── FlexBoxAdvancedMenuItems.cs
│ │ └── (otros archivos del editor)
│ └── FlexGraphic/
│ ├── FlexGraphic.cs
│ └── Editor/
│ └── FlexGraphicEditor.cs
⚠️ Verificación Importante
Antes de continuar, verifica que todos los archivos estén en su lugar y no haya errores de compilación en Unity. Si faltan archivos, contacta con el desarrollador del sistema.
Paso 2: Crear un Canvas Base
- Crear Canvas:
- Clic derecho en Hierarchy → UI → Canvas
- Configurar Canvas Scaler para "Scale With Screen Size"
- Establecer Reference Resolution (ej: 1920x1080)
- Configurar Canvas Scaler:
UI Scale Mode: Scale With Screen Size Reference Resolution: 1920 x 1080 Screen Match Mode: Match Width Or Height Match: 0.5
📦 Implementación de FlexBox
Paso 1: Crear tu Primer FlexBox
Método 1: Desde el Menú (Recomendado)
- Clic derecho en Hierarchy → UI → FlexBox
- Unity creará automáticamente un GameObject con RectTransform y FlexBox
- El componente se configurará con valores por defecto óptimos
Método 2: Manual
- Crear GameObject vacío
- Agregar RectTransform (automático al estar bajo Canvas)
- Agregar componente FlexBox desde Add Component → Layout → Flex Box
Paso 2: Configurar Propiedades del Contenedor
Propiedades Principales del Contenedor:
| Propiedad | Opciones Disponibles | Descripción | Uso Común |
|---|---|---|---|
| Direction | Column, Row, ColumnReverse, RowReverse | Dirección principal del layout | Column para listas verticales, Row para barras horizontales |
| Wrap | NoWrap, Wrap, WrapReverse | Comportamiento cuando no hay espacio | Wrap para grids adaptativos |
| Justify Content | FlexStart, FlexEnd, Center, SpaceBetween, SpaceAround, SpaceEvenly | Alineación en el eje principal | Center para centrar, SpaceBetween para distribuir |
| Align Items | Stretch, FlexStart, FlexEnd, Center | Alineación en el eje cruzado | Center para alineación vertical, Stretch para llenar |
Ejemplo Práctico - Barra de Navegación:
// Configuración para una barra de navegación horizontal
flexBox.direction = FlexDirection.Row;
flexBox.justifyContent = JustifyContent.SpaceBetween;
flexBox.alignItems = AlignItems.Center;
flexBox.padding = new FlexSpacing(20f, 10f, 20f, 10f); // top, right, bottom, left
flexBox.gap = 15f;
🎨 Implementación de FlexGraphic
Paso 1: Crear un FlexGraphic
- Crear GameObject:
- Crear GameObject vacío (Clic derecho → Create Empty)
- Asegurar que tenga RectTransform
- Add Component → UI → Flex Graphic
- Configuración Inicial:
Color: Blanco (255, 255, 255, 255) Material: UI/Default (se asigna automáticamente) Raycast Target: True (para interacción) Maskable: True (para soporte de máscaras)
Paso 2: Configurar Esquinas Redondeadas
Configuraciones de Esquinas:
⚠️ Rendimiento
El Corner Quality afecta directamente el rendimiento. Usa valores entre 4-8 para UI general, y 10-15 solo para elementos destacados que requieren máxima calidad visual.
| Configuración | Valor Recomendado | Uso |
|---|---|---|
| Corner Radius | 8-25 píxeles | Botones y paneles generales |
| Corner Quality | 6-8 | Balance entre calidad y rendimiento |
| Individual Corners | Según diseño | Formas asimétricas y diseños únicos |
Ejemplos de Configuración:
// Botón estándar
cornerRadius = 12f;
cornerQuality = 6;
// Panel de diálogo
cornerRadius = 20f;
useIndividualCorners = true;
topLeftRadius = 20f;
topRightRadius = 20f;
bottomLeftRadius = 8f;
bottomRightRadius = 8f;
// Elemento de lista
cornerRadius = 8f;
cornerQuality = 4;
Paso 3: Configurar Bordes
Configuración de Bordes:
// Borde básico
drawBorder = true;
borderWidth = 2f;
borderColor = new Color(1f, 1f, 1f, 0.8f); // Blanco semi-transparente
// Borde con gradiente
drawBorder = true;
borderWidth = 3f;
useBorderGradient = true;
borderGradientType = GradientType.LinearLeftToRight;
🛠️ Casos de Uso Prácticos
Caso 1: Panel de Login Responsivo
Estructura Completa del Panel:
LoginPanel (FlexBox Container + FlexGraphic Background)
├── HeaderSection (FlexBox)
│ ├── Logo (Image + FlexGraphic)
│ └── Title (TextMeshPro)
├── FormSection (FlexBox)
│ ├── UsernameGroup (FlexBox)
│ │ ├── UsernameLabel (TextMeshPro)
│ │ └── UsernameField (InputField + FlexGraphic)
│ ├── PasswordGroup (FlexBox)
│ │ ├── PasswordLabel (TextMeshPro)
│ │ └── PasswordField (InputField + FlexGraphic)
│ └── ButtonGroup (FlexBox)
│ ├── LoginButton (Button + FlexGraphic)
│ └── CancelButton (Button + FlexGraphic)
└── FooterSection (FlexBox)
├── RememberMe (Toggle + FlexGraphic)
└── ForgotPassword (Button + FlexGraphic)
Configuración Paso a Paso:
1. Panel Principal (LoginPanel):
// FlexBox Configuration
direction = FlexDirection.Column;
justifyContent = JustifyContent.Center;
alignItems = AlignItems.Center;
padding = new FlexSpacing(40f);
gap = 30f;
// FlexGraphic Configuration
cornerRadius = 25f;
drawBorder = true;
borderWidth = 2f;
borderColor = new Color(1f, 1f, 1f, 0.3f);
color = new Color(0.1f, 0.1f, 0.1f, 0.9f); // Fondo oscuro semi-transparente
2. Sección de Formulario:
// FormSection FlexBox
direction = FlexDirection.Column;
justifyContent = JustifyContent.FlexStart;
alignItems = AlignItems.Stretch;
gap = 20f;
width = new FlexSize(350f); // Ancho fijo
height = FlexSize.Auto; // Alto automático
Caso 2: Grid de Productos Adaptativo
Configuración del Grid Adaptativo:
// Container principal
gridContainer.direction = FlexDirection.Row;
gridContainer.wrap = FlexWrap.Wrap;
gridContainer.justifyContent = JustifyContent.SpaceEvenly;
gridContainer.alignItems = AlignItems.Stretch;
gridContainer.gap = 20f;
gridContainer.padding = new FlexSpacing(30f);
// Cada item del grid
productItem.flexGrow = 0;
productItem.flexShrink = 1;
productItem.width = new FlexSize(280f); // Ancho base
productItem.minWidth = new FlexSize(200f); // Mínimo
productItem.maxWidth = new FlexSize(350f); // Máximo
productItem.height = new FlexSize(320f);
🔧 Troubleshooting y Problemas Comunes
Problemas con FlexBox
❌ Problema: Los elementos no se alinean correctamente
Síntomas: Los elementos hijos no respetan la alineación configurada o se superponen
Causas comunes:
- Elementos hijos sin RectTransform
- Propiedades de tamaño incorrectas
- Conflictos con otros Layout Groups
Soluciones paso a paso:
// 1. Verificar RectTransform en elementos hijos
foreach (Transform child in transform)
{
if (child.GetComponent<RectTransform>() == null)
{
Debug.LogWarning($"Child {child.name} missing RectTransform!");
child.gameObject.AddComponent<RectTransform>();
}
}
// 2. Configurar propiedades de tamaño apropiadas
childFlexBox.width = FlexSize.Auto; // Para tamaño automático
childFlexBox.height = FlexSize.Auto;
childFlexBox.flexGrow = 1f; // Para crecimiento flexible
childFlexBox.flexShrink = 1f; // Para reducción flexible
// 3. Forzar recálculo del layout
flexBox.SetDirty();
flexBox.ForceRebuildLayout();
❌ Problema: Layout no se actualiza en tiempo real
Síntomas: Los cambios en el Inspector no se reflejan inmediatamente
Soluciones:
// En el Inspector, usar el menú contextual:
// Clic derecho en FlexBox → Force Rebuild Layout
// Por código:
flexBox.SetDirty();
LayoutRebuilder.MarkLayoutForRebuild(flexBox.rectTransform);
// Para debugging:
flexBox.LogLayoutInfo(); // Muestra información detallada en consola
Problemas con FlexGraphic
❌ Problema: Esquinas no se renderizan correctamente
Síntomas: Las esquinas se ven pixeladas, cortadas o no aparecen
Soluciones:
// 1. Ajustar calidad de esquinas
flexGraphic.cornerQuality = 8; // Incrementar para mejor calidad
// 2. Verificar que el radio no exceda las dimensiones
float maxRadius = Mathf.Min(width, height) * 0.5f;
flexGraphic.cornerRadius = Mathf.Min(flexGraphic.cornerRadius, maxRadius);
// 3. Asegurar que el GameObject tenga CanvasRenderer
if (GetComponent<CanvasRenderer>() == null)
{
gameObject.AddComponent<CanvasRenderer>();
}
📚 Referencias Avanzadas y API Completa
API Completa de FlexBox
| Categoría | Propiedades | Tipo | Descripción |
|---|---|---|---|
| Container | direction | FlexDirection | Dirección principal del layout |
| wrap | FlexWrap | Comportamiento de ajuste de líneas | |
| justifyContent | JustifyContent | Alineación en el eje principal | |
| alignItems | AlignItems | Alineación en el eje cruzado | |
| alignContent | AlignContent | Alineación de líneas múltiples | |
| gap | float | Espacio entre elementos hijos | |
| padding | FlexSpacing | Espaciado interno del contenedor | |
| Item | flexGrow | float | Factor de crecimiento |
| flexShrink | float | Factor de reducción | |
| flexBasis | FlexSize | Tamaño base antes de crecimiento/reducción | |
| alignSelf | AlignSelf | Alineación individual del elemento | |
| order | int | Orden visual del elemento | |
| width/height | FlexSize | Dimensiones del elemento | |
| minWidth/maxWidth | FlexSize | Restricciones de tamaño | |
| margin | FlexSpacing | Espaciado externo del elemento |
Mejores Prácticas y Recomendaciones
🎯 Mejores Prácticas para FlexBox
- Usa Gap en lugar de Margin: Para espaciado consistente entre elementos hermanos
- Configura Min/Max constraints: Para prevenir tamaños extremos en dispositivos diferentes
- Usa Auto sizing: Para layouts que se adaptan automáticamente al contenido
- Combina con Layout Groups: Para layouts complejos anidados cuando sea necesario
- Planifica la jerarquía: Diseña la estructura antes de implementar
🎨 Mejores Prácticas para FlexGraphic
- Optimiza Corner Quality: Usa 4-6 para UI general, 8-12 para elementos destacados
- Usa Individual Corners: Para diseños únicos y asimétricos
- Aplica Falloff: Para bordes suaves y apariencia profesional
- Combina con Gradientes: Para efectos visuales modernos
- Considera el rendimiento: Evita muchos FlexGraphic complejos en pantalla simultáneamente
🎉 ¡Felicitaciones!
Has completado la guía completa de implementación del sistema FlexBox y FlexGraphic. Ahora tienes todas las herramientas y conocimientos necesarios para crear interfaces de usuario flexibles, responsivas y visualmente atractivas en Unity.
Próximos pasos sugeridos:
- Experimenta con diferentes combinaciones de propiedades
- Crea tus propios componentes basados en FlexBox/FlexGraphic
- Desarrolla patrones de diseño reutilizables para tu proyecto
- Explora las características avanzadas como gradientes y efectos
Complete Implementation Guide: FlexBox and FlexGraphic System for Unity
📋 Document Information
Version: 2.0 | Compatibility: Unity 2022.3 LTS+ | Date: September 2024
This guide will teach you step by step how to implement and use the FlexBox and FlexGraphic system in Unity, from initial setup to advanced use cases.
🌙 New features: Dark and light theme support, improved navigation, and responsive design.
🚀 System Introduction
What is FlexBox and FlexGraphic?
The FlexBox and FlexGraphic system is a complete CSS Flexbox implementation for Unity UI that allows creating flexible and responsive layouts intuitively.
✨ System Advantages
- ✅ Automatic responsive layouts
- ✅ Precise alignment without manual calculations
- ✅ Consistent spacing between elements
- ✅ Full support for different screen sizes
- ✅ Native integration with Unity's Layout system
- ✅ Advanced graphic components with rounded corners
⚙️ Initial Setup
Step 1: Verify Project Structure
Make sure your project has the following structure:
Assets/
├── FlexUI/
│ ├── FlexBox/
│ │ ├── FlexBox.cs
│ │ ├── FlexElement.cs
│ │ ├── FlexEnums.cs
│ │ ├── FlexLayout.cs
│ │ ├── FlexLayoutCalculator.cs
│ │ ├── FlexPositioner.cs
│ │ ├── FlexSizeCalculator.cs
│ │ ├── FlexUtility.cs
│ │ ├── FlexChildrenManager.cs
│ │ ├── IFlexContainer.cs
│ │ ├── IFlexItem.cs
│ │ └── Editor/
│ │ ├── FlexBoxEditor.cs
│ │ ├── FlexBoxAdvancedMenuItems.cs
│ │ └── (other editor files)
│ └── FlexGraphic/
│ ├── FlexGraphic.cs
│ └── Editor/
│ └── FlexGraphicEditor.cs
⚠️ Important Verification
Before continuing, verify that all files are in place and there are no compilation errors in Unity. If files are missing, contact the system developer.
Step 2: Create a Base Canvas
- Create Canvas:
- Right-click in Hierarchy → UI → Canvas
- Configure Canvas Scaler for "Scale With Screen Size"
- Set Reference Resolution (e.g., 1920x1080)
- Configure Canvas Scaler:
UI Scale Mode: Scale With Screen Size Reference Resolution: 1920 x 1080 Screen Match Mode: Match Width Or Height Match: 0.5
📦 FlexBox Implementation
Step 1: Create Your First FlexBox
Method 1: From Menu (Recommended)
- Right-click in Hierarchy → UI → FlexBox
- Unity will automatically create a GameObject with RectTransform and FlexBox
- The component will be configured with optimal default values
Method 2: Manual
- Create empty GameObject
- Add RectTransform (automatic when under Canvas)
- Add FlexBox component from Add Component → Layout → Flex Box
Step 2: Configure Container Properties
Main Container Properties:
| Property | Available Options | Description | Common Use |
|---|---|---|---|
| Direction | Column, Row, ColumnReverse, RowReverse | Main layout direction | Column for vertical lists, Row for horizontal bars |
| Wrap | NoWrap, Wrap, WrapReverse | Behavior when there's no space | Wrap for adaptive grids |
| Justify Content | FlexStart, FlexEnd, Center, SpaceBetween, SpaceAround, SpaceEvenly | Main axis alignment | Center to center, SpaceBetween to distribute |
| Align Items | Stretch, FlexStart, FlexEnd, Center | Cross axis alignment | Center for vertical alignment, Stretch to fill |
Practical Example - Navigation Bar:
// Configuration for a horizontal navigation bar
flexBox.direction = FlexDirection.Row;
flexBox.justifyContent = JustifyContent.SpaceBetween;
flexBox.alignItems = AlignItems.Center;
flexBox.padding = new FlexSpacing(20f, 10f, 20f, 10f); // top, right, bottom, left
flexBox.gap = 15f;
🎨 FlexGraphic Implementation
Step 1: Create a FlexGraphic
- Create GameObject:
- Create empty GameObject (Right-click → Create Empty)
- Ensure it has RectTransform
- Add Component → UI → Flex Graphic
- Initial Configuration:
Color: White (255, 255, 255, 255) Material: UI/Default (assigned automatically) Raycast Target: True (for interaction) Maskable: True (for mask support)
Step 2: Configure Rounded Corners
Corner Configurations:
⚠️ Performance
Corner Quality directly affects performance. Use values between 4-8 for general UI, and 10-15 only for featured elements that require maximum visual quality.
| Setting | Recommended Value | Use Case |
|---|---|---|
| Corner Radius | 8-25 pixels | General buttons and panels |
| Corner Quality | 6-8 | Balance between quality and performance |
| Individual Corners | As per design | Asymmetric shapes and unique designs |
Configuration Examples:
// Standard button
cornerRadius = 12f;
cornerQuality = 6;
// Dialog panel
cornerRadius = 20f;
useIndividualCorners = true;
topLeftRadius = 20f;
topRightRadius = 20f;
bottomLeftRadius = 8f;
bottomRightRadius = 8f;
// List item
cornerRadius = 8f;
cornerQuality = 4;
🛠️ Practical Use Cases
Case 1: Responsive Login Panel
Complete Panel Structure:
LoginPanel (FlexBox Container + FlexGraphic Background)
├── HeaderSection (FlexBox)
│ ├── Logo (Image + FlexGraphic)
│ └── Title (TextMeshPro)
├── FormSection (FlexBox)
│ ├── UsernameGroup (FlexBox)
│ │ ├── UsernameLabel (TextMeshPro)
│ │ └── UsernameField (InputField + FlexGraphic)
│ ├── PasswordGroup (FlexBox)
│ │ ├── PasswordLabel (TextMeshPro)
│ │ └── PasswordField (InputField + FlexGraphic)
│ └── ButtonGroup (FlexBox)
│ ├── LoginButton (Button + FlexGraphic)
│ └── CancelButton (Button + FlexGraphic)
└── FooterSection (FlexBox)
├── RememberMe (Toggle + FlexGraphic)
└── ForgotPassword (Button + FlexGraphic)
🔧 Troubleshooting and Common Problems
❌ Problem: Elements don't align correctly
Symptoms: Child elements don't respect configured alignment or overlap
Solution: Verify that child elements have RectTransform and size properties configured correctly.
// Verify child elements have RectTransform
foreach (Transform child in transform)
{
if (child.GetComponent<RectTransform>() == null)
{
Debug.LogWarning($"Child {child.name} missing RectTransform!");
child.gameObject.AddComponent<RectTransform>();
}
}
// Configure appropriate size properties
childFlexBox.width = FlexSize.Auto; // For automatic size
childFlexBox.height = FlexSize.Auto;
childFlexBox.flexGrow = 1f; // For flexible growth
childFlexBox.flexShrink = 1f; // For flexible shrinking
📚 Advanced References and Complete API
🎉 Congratulations!
You have completed the complete implementation guide for the FlexBox and FlexGraphic system. You now have all the tools and knowledge necessary to create flexible, responsive, and visually appealing user interfaces in Unity.
Suggested next steps:
- Experiment with different property combinations
- Create your own components based on FlexBox/FlexGraphic
- Develop reusable design patterns for your project
- Explore advanced features like gradients and effects