Version: 2018.4
Controles
Modos de Diseño

Personalización

Personalizando sus controles IMGUI

Aunque el sistema IMGUI de Unity tiene el propósito principal de crear herramientas de desarrollo e interfaces de depuración, usted todavía puede personalizar y estilarlas como quiera. En el sistema IMGUI de Unity, usted puede ajustar finamente la apariencia de sus controles con muchos detalles. El control de las apariencias se dicta con GUIStyles. Por defecto, cuando usted cree un Control sin definir un GUIStyle, el GUIStyle por defecto de Unity es aplicado. Este estilo es interno en Unity y se puede utilizar en los juegos publicados para un prototyping rápido, o si usted escoge no estilar su controles.

Cuando usted tiene un grande número de diferentes GUIStyles con los que tiene que trabajar, usted puede definirlos todos dentro una sola GUISkin. Una GUISkin no es mas que una colección de GUIStyles.

Cómo los Estilos cambian el aspecto de sus controles GUI

Los GUIStyles son diseñados para imitar Cascading Style Sheets (CSS) para los navegadores web. Muchas metodologías CSS han sido adaptadas, incluyendo la diferenciación de las propiedades de cada estado para estilizar, y la separación entre el contenido y la apariencia.

Donde el Control definen el contenido, el Style define la apariencia. Esto le permite crear combinaciones como una Toggle funcional que se aparece como un botón Button.

Los dos controles Toggle estilados diferentemente
Los dos controles Toggle estilados diferentemente

La diferencia entre pieles y estilo

Como se menciono anteriormente, los GUISkins son una colección de GUIstyles. Los Estilos definen la apariencia de un Control GUI. Usted no tiene que usar una Piel si usted quiere utilizar un Estilo.

Un solo GUIStyle mostrado en el Inspector
Un solo GUIStyle mostrado en el Inspector

Un solo GUISkin mostrado en el Inspector - observe que tiene varios GUIStyles

Trabajando con Estilos(Styles)

Todas las funciones de Controles GUI tienen un último parámetro opcional: el GUIStyle que se usa para mostrar el Control. Si este es omitido, el GUIStyle predeterminado de Unity será usado. Esto funciona internamente al aplicar el nombre del tipo de control como un string, entonces GUI.Button() utiliza el estilo del “botón”, GUI.Toggle() utiliza el estilo de “palanca(toggle)”, etc. Usted puede anular el GUIStyle predeterminado para un Control especificándolo como el último parámetro.

/* Override the default Control Style with a different style in the UnityGUI default Styles */


// JavaScript
function OnGUI () {
    // Make a label that uses the "box" GUIStyle.
    GUI.Label (Rect (0,0,200,100), "Hi - I'm a label looking like a box", "box");

    // Make a button that uses the "toggle" GUIStyle
    GUI.Button (Rect (10,140,180,20), "This is a button", "toggle");
}


// C#
using UnityEngine;
using System.Collections;

public class GUITest : MonoBehaviour {
                    
    void OnGUI () {
        // Make a label that uses the "box" GUIStyle.
        GUI.Label (new Rect (0,0,200,100), "Hi - I'm a label looking like a box", "box");
    
        // Make a button that uses the "toggle" GUIStyle
        GUI.Button (new Rect (10,140,180,20), "This is a button", "toggle");
    }

}


Los controles creados por el código ejemplo de arriba
Los controles creados por el código ejemplo de arriba

Haciendo una variable pública GUIStyle

Cuando usted declara una variable GUIStyle, todos los elementos de el Style deben aparecer en el Inspector. Usted puede editar todos los diferentes valores aquí.

/* Overriding the default Control Style with one you've defined yourself */


// JavaScript
var customButton : GUIStyle;

function OnGUI () {
    // Make a button. We pass in the GUIStyle defined above as the style to use
    GUI.Button (Rect (10,10,150,20), "I am a Custom Button", customButton);
}


// C#
using UnityEngine;
using System.Collections;

public class GUITest : MonoBehaviour {
                    
    public GUIStyle customButton;
    
    void OnGUI () {
        // Make a button. We pass in the GUIStyle defined above as the style to use
        GUI.Button (new Rect (10,10,150,20), "I am a Custom Button", customButton);
    }
    
}


Cambiando los diferentes estilo de los elementos

Cuando usted ha declarado un GUIStyle, usted puede modificar ese estilo en el inspector. Hay un gran número de Estados que usted puede definir, y aplicar a cualquier tipo de Control.

Los estilos se modifican en una base per-script per-GameObject
Los estilos se modifican en una base per-script per-GameObject

Cualquier Estado de Control(Control State) debe tener asignado un Color Background antes de que el Text Color especificado sea aplicado.

Para más información acerca de GUIStyles individuales, por favor lea GUIStyle Component Reference page.

Trabajando con Pieles(Skins)

Para sistemas GUI más complicados, tiene sentido mantener una colección de estilos en un solo lugar. Esto es lo que un GUISkin hace. Un GUISkin contiene múltiples estilos diferentes, esencialmente proporcionando un levantamiento a todos los controles GUI.

Creando un nuevo GUISkins

Para crear un GUISkin, seleccione Assets->Create->GUI Skin de la barra del menú. Esto va a crear una GUI Skin en su carpeta Project. Seleccione esta para ver todos los GUIStyles definidos por el Skin en el inspector.

Aplicando la piel(Skin) a un GUI

Para utilizar una piel(skin) que usted ha creado, asígnela al GUI.skin a su función OnGUI() function.

/* Make a property containing a reference to the skin you want to use */


// JavaScript
var mySkin : GUISkin;

function OnGUI () {
    // Assign the skin to be the one currently used.
    GUI.skin = mySkin;

    // Make a button. This will get the default "button" style from the skin assigned to mySkin.
    GUI.Button (Rect (10,10,150,20), "Skinned Button");
}


// C#
using UnityEngine;
using System.Collections;

public class GUITest : MonoBehaviour {
                    
    public GUISkin mySkin;
    
    void OnGUI () {
        // Assign the skin to be the one currently used.
        GUI.skin = mySkin;
    
        // Make a button. This will get the default "button" style from the skin assigned to mySkin.
        GUI.Button (new Rect (10,10,150,20), "Skinned Button");
    }
        
}
98 words

You can switch skins as much as you like throughout a single __OnGUI()__ call.
14 words
Usted puede cambiar pieles(skins) las veces que usted quiere a través una sola llamada __OnGUI()__.
100%

/* Example of switching skins in the same OnGUI() call */


// JavaScript
var mySkin : GUISkin;

var toggle = true;

function OnGUI () {
    // Assign the skin to be the one currently used.
    GUI.skin = mySkin;

    // Make a toggle. This will get the "button" style from the skin assigned to mySkin.
    toggle = GUI.Toggle (Rect (10,10,150,20), toggle, "Skinned Button", "button");

    // Assign the currently skin to be Unity's default.
    GUI.skin = null;

    // Make a button. This will get the default "button" style from the built-in skin.
    GUI.Button (Rect (10,35,150,20), "Built-in Button");
}


// C#
using UnityEngine;
using System.Collections;

public class GUITest : MonoBehaviour {
                    
    public GUISkin mySkin;
    private bool toggle = true;
    
    void OnGUI () {
        // Assign the skin to be the one currently used.
        GUI.skin = mySkin;
    
        // Make a toggle. This will get the "button" style from the skin assigned to mySkin.
        toggle = GUI.Toggle (new Rect (10,10,150,20), toggle, "Skinned Button", "button");
    
        // Assign the currently skin to be Unity's default.
        GUI.skin = null;
    
        // Make a button. This will get the default "button" style from the built-in skin.
        GUI.Button (new Rect (10,35,150,20), "Built-in Button");
    }
        
}


Usted puede cambiar pieles(skins) las veces que usted quiere a través una sola llamada OnGUI().

/* Example of switching skins in the same OnGUI() call */


// JavaScript
var mySkin : GUISkin;

var toggle = true;

function OnGUI () {
    // Assign the skin to be the one currently used.
    GUI.skin = mySkin;

    // Make a toggle. This will get the "button" style from the skin assigned to mySkin.
    toggle = GUI.Toggle (Rect (10,10,150,20), toggle, "Skinned Button", "button");

    // Assign the currently skin to be Unity's default.
    GUI.skin = null;

    // Make a button. This will get the default "button" style from the built-in skin.
    GUI.Button (Rect (10,35,150,20), "Built-in Button");
}


// C#
using UnityEngine;
using System.Collections;

public class GUITest : MonoBehaviour {
                    
    public GUISkin mySkin;
    private bool toggle = true;
    
    void OnGUI () {
        // Assign the skin to be the one currently used.
        GUI.skin = mySkin;
    
        // Make a toggle. This will get the "button" style from the skin assigned to mySkin.
        toggle = GUI.Toggle (new Rect (10,10,150,20), toggle, "Skinned Button", "button");
    
        // Assign the currently skin to be Unity's default.
        GUI.skin = null;
    
        // Make a button. This will get the default "button" style from the built-in skin.
        GUI.Button (new Rect (10,35,150,20), "Built-in Button");
    }
        
}


Cambiando el Tamaño de Fuente del GUI

Este ejemplo le va a mostrar cómo cambiar dinámicamente el tamaño fuente a través del código.

Primero cree un nuevo Proyecto en Unity. Luego haga un script C# llamada Fontsize.cs y pegue el siguiente código en:

// C# example
using UnityEngine;
    
using System.Collections;
    
public class Fontsize : MonoBehaviour
{
    void OnGUI ()
    {
        //Set the GUIStyle style to be label
        GUIStyle style = GUI.skin.GetStyle ("label");
        
        //Set the style font size to increase and decrease over time
        style.fontSize = (int)(20.0f + 10.0f * Mathf.Sin (Time.time));
        
        //Create a label and display with the current settings
        GUI.Label (new Rect (10, 10, 200, 80), "Hello World!");
    }
        
}

Guarde el script y adjúntelo a un GameObject vacío, haga click en reproducir para ver el ciclo de la fuente a través del aumento y la disminución del tamaño en el tiempo. Usted puede notar que la fuente no cambia con suavidad el tamaño, esto se debe a que no hay un número infinito de tamaños de fuente.

Este ejemplo específico requiere que la fuente predeterminada (Arial) es cargada y marcada como dinámica. Usted no puede cambiar el tamaño de fuente de cualquier fuente que no esté marcada como dinámica.

Controles
Modos de Diseño