Iconos integrados de Unity

Al crear herramientas de Unity, aunque la funcionalidad es importante, la estética también lo es. Por lo tanto, será mejor utilizar los íconos integrados de Unity.

Entonces la pregunta es, ¿cómo se obtienen los íconos integrados de Unity?

Yusong MOMO escribió un blog, descompiló el dll del editor y extrajo la información del ícono usando expresiones regulares. ¿Pero qué debo hacer si no he visto la descompilación? [Yusong MOMO: Su ícono ]

De hecho, existen otros métodos. Podemos usar directamente FindObjectsOfTypeAll of Resources para echar un vistazo primero.

/*
 * 查看所有 Textures
 * 
 * 
 * 
 */


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class UnityIconsWindow : EditorWindow
{
    
    

    [MenuItem(("JJJ/Unity Textures Window"))]
    static void Init()
    {
    
    
        UnityIconsWindow window = EditorWindow.GetWindow<UnityIconsWindow>("Unity Textures Window");
        //加载所有Texture2D
        window.textures = Resources.FindObjectsOfTypeAll<Texture2D>();
        window.minSize = new Vector2(200, 400);

        //用于GUI
        window.fullRect = new Rect();
        foreach (var texture in window.textures)
        {
    
    
            window.fullRect.height += texture.height + 15 + 5 + 10;
        }
    }

    Vector2 scrollPos;

    Texture2D[] textures;

    Rect fullRect;

    void OnGUI()
    {
    
    
        Rect scrollrect = new Rect();
        scrollrect.width = position.width;
        scrollrect.height = position.height;

        scrollPos = GUI.BeginScrollView(scrollrect, scrollPos, fullRect);

        Rect r = new Rect();
        r.x = 10;

        Rect box = new Rect();
        box.x = 7;
        box.width = position.width - 30;

        foreach (Texture2D texture in textures)
        {
    
    
            box.y = r.y;
            box.height = 15 + 5 + texture.height + 2;
            GUI.Box(box, "");

            r.height = 15;
            r.width = position.width;
            //绘制名字
            GUI.Label(r, texture.name);
            r.y += r.height;

            r.y += 5;

            r.height = texture.height;
            r.width = texture.width;
            //绘制图标
            GUI.DrawTexture(r, texture);
            r.y += texture.height;

            r.y += 10;
        }
        GUI.EndScrollView();
    }
}

A continuación, podremos ver muchos iconos que hemos visto antes.
Es mejor crear un nuevo proyecto vacío, porque también se cargará la textura propia del proyecto.

Insertar descripción de la imagen aquí

Pero encontré algunos problemas: ¿Algunos campos de nombre de textura están vacíos?

Insertar descripción de la imagen aquí
¿Esta bien? Pero está bien, no es un gran problema, no los usamos.

Ahora que vemos estas imágenes, ¿cómo las usamos en nuestras herramientas? No puedes cargarlo cada vez que lo usas, luego recorrerlo y elegir los que tienen el mismo nombre, ¿verdad?

De hecho, Unity tiene una API para obtener un ícono específico por su nombre.

	public static GUIContent IconContent (string name, string text= null);
	
	//name	所需图标的名称。
	//text	悬停在图标上的工具提示。

	//从具有给定名称的 Unity 内置资源中获取 GUIContent。
	//EditorGUIUtility.IconContent 用于为 GUI 元素创建 GUIContent。 
	//只会加载图标.通常情况下,将使用第一个参数获取 Assets/Editor Default 	Resources/Icons 中的图标。 
	//只需要图标的名称,而不需要 png 扩展名。 \ 第二个参数为悬停工具提示提供文本。
	//此字符串 需要以竖线“|”字符开头以将其标记为工具提示。
	//注意:目前无法悬停定位在工具提示上方。

Para crear un GUIContent, simplemente usa esta API. ¿Qué pasa si solo quieres una textura? Eso también es muy simple,

     Texture texture = EditorGUIUtility.IconContent("IconName").image;

Pero, de hecho, no todos los íconos se pueden recuperar a través de esta función. Solo los íconos en Activos/Recursos predeterminados del editor/Iconos se pueden recuperar con esta función .

Cambiemos el script anterior:

  /*
 * 查看所有 Textures
 * 
 * 
 * 
 */


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class UnityIconsWindow : EditorWindow
{
    
    

    [MenuItem(("JJJ/Unity Textures Window"))]
    static void Init()
    {
    
    
        UnityIconsWindow window = EditorWindow.GetWindow<UnityIconsWindow>("Unity Textures Window");
        //加载所有Texture2D
        window.textures = Resources.FindObjectsOfTypeAll<Texture2D>();
        window.minSize = new Vector2(200, 400);


        //可见
        window.textures2 = new Texture2D[window.textures.Length];
        for (int i = 0; i < window.textures2.Length; i++)
        {
    
    
            window.textures2[i] = EditorGUIUtility.IconContent(window.textures[i].name).image as Texture2D;
        }


        //用于GUI
        window.fullRect = new Rect();
        //foreach (var texture in window.textures)
        //{
    
    
        //    window.fullRect.height += texture.height + 15 + 5 + 10;
        //}
        for (int i = 0; i < window.textures2.Length; i++)
        {
    
    
            if (window.textures2[i] != null)
            {
    
    
                window.fullRect.height += window.textures2[i].height + 15 + 5 + 10;
            }
        }
    }

    Vector2 scrollPos;

    Texture2D[] textures;

    Texture2D[] textures2;

    Rect fullRect;

    void OnGUI()
    {
    
    
        Rect scrollrect = new Rect();
        scrollrect.width = position.width;
        scrollrect.height = position.height;

        scrollPos = GUI.BeginScrollView(scrollrect, scrollPos, fullRect);

        Rect r = new Rect();
        r.x = 10;

        Rect box = new Rect();
        box.x = 7;
        box.width = position.width - 30;

        foreach (Texture2D texture in textures2)
        {
    
    
            if (texture == null) continue;

            box.y = r.y;
            box.height = 15 + 5 + texture.height + 2;
            GUI.Box(box, "");

            r.height = 15;
            r.width = position.width;
            //绘制名字
            GUI.Label(r, texture.name);
            r.y += r.height;

            r.y += 5;

            r.height = texture.height;
            r.width = texture.width;
            //绘制图标
            GUI.DrawTexture(r, texture);
            r.y += texture.height;

            r.y += 10;
        }
        GUI.EndScrollView();
    }

    private void OnDisable()
    {
    
    
        textures = null;
    }
}

Ventana abierta:

Insertar descripción de la imagen aquí

Es obvio por el informe de error: o proporciona la ruta completa al proyecto de la imagen (incluida la extensión) , o debe ser el nombre del icono en Activos/Recursos predeterminados del editor/Iconos (sin la extensión) .

Entonces, primero ocultemos el error y luego intentemos darle una ruta completa del proyecto:

/*
 * 查看所有 Textures
 * 
 * 
 * 
 */


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class UnityIconsWindow : EditorWindow
{
    
    

    [MenuItem(("JJJ/Unity Textures Window"))]
    static void Init()
    {
    
    
        UnityIconsWindow window = EditorWindow.GetWindow<UnityIconsWindow>("Unity Textures Window");
        //加载所有Texture2D
        window.textures = Resources.FindObjectsOfTypeAll<Texture2D>();
        window.minSize = new Vector2(200, 400);


        //可见
        window.textures2 = new Texture2D[window.textures.Length];
        Debug.unityLogger.logEnabled = false;//关掉那个报错,不用管它
        for (int i = 0; i < window.textures2.Length; i++)
        {
    
    
            if (window.textures[i].name == "微信图片_20210808203939")//这样写很愚蠢,只是为了作为一个例子才这样写
                window.textures2[i] = EditorGUIUtility.IconContent(AssetDatabase.GetAssetPath(window.textures[i])).image as Texture2D;
            else
                window.textures2[i] = EditorGUIUtility.IconContent(window.textures[i].name).image as Texture2D;
        }
        Debug.unityLogger.logEnabled = true;

        //用于GUI
        window.fullRect = new Rect();
        //foreach (var texture in window.textures)
        //{
    
    
        //    window.fullRect.height += texture.height + 15 + 5 + 10;
        //}
        for (int i = 0; i < window.textures2.Length; i++)
        {
    
    
            if (window.textures2[i] != null)
            {
    
    
                window.fullRect.height += window.textures2[i].height + 15 + 5 + 10;
            }
        }
    }

    Vector2 scrollPos;

    Texture2D[] textures;

    Texture2D[] textures2;

    Rect fullRect;

    void OnGUI()
    {
    
    
        Rect scrollrect = new Rect();
        scrollrect.width = position.width;
        scrollrect.height = position.height;

        scrollPos = GUI.BeginScrollView(scrollrect, scrollPos, fullRect);

        Rect r = new Rect();
        r.x = 10;

        Rect box = new Rect();
        box.x = 7;
        box.width = position.width - 30;

        foreach (Texture2D texture in textures2)
        {
    
    
            if (texture == null) continue;

            box.y = r.y;
            box.height = 15 + 5 + texture.height + 2;
            GUI.Box(box, "");

            r.height = 15;
            r.width = position.width;
            //绘制名字
            GUI.Label(r, texture.name);
            r.y += r.height;

            r.y += 5;

            r.height = texture.height;
            r.width = texture.width;
            //绘制图标
            GUI.DrawTexture(r, texture);
            r.y += texture.height;

            r.y += 10;
        }
        GUI.EndScrollView();
    }

    private void OnDisable()
    {
    
    
        textures = null;
    }
}

Abre la ventana nuevamente:

Insertar descripción de la imagen aquí
Perfecto, puedes ver el primero.

Entonces podemos considerar tener una clase de herramienta de este tipo. Cuando necesitemos Icon, solo necesitamos usar este script.

using UnityEngine;
using UnityEditor;

public static class JIconUtility
{
    
    
    //比如需要一个文件夹图标,就可以这样写
    static Texture2D directoryIcon;
    public static Texture2D DirectoryIcon {
    
     get {
    
     if (directoryIcon == null) directoryIcon = EditorGUIUtility.IconContent("Folder Icon").image as Texture2D; return directoryIcon; } }

    //其他的你自定义的icon其实也可以放在这里,只不过不是用 EditorGUIUtility.IconContent() ,而是要直接 Resources.Load 加载
    static Texture2D myIcon;
    public static Texture2D MyIcon {
    
     get {
    
     if (myIcon == null) myIcon = Resources.Load<Texture2D>("MyIcon"/*自定义icon路径*/); return myIcon; } }
}

O también puedes usar EditorGUIUtility.Load() o EditorGUIUtility.LoadRequired() para cargar recursos integrados.

Supongo que te gusta

Origin blog.csdn.net/weixin_44293055/article/details/120443635
Recomendado
Clasificación