1
\$\begingroup\$

How can I add a picture in the Hierarchy view in Unity? For example, Dragon bones does it automatically. Here it is :

enter image description here

As you can see there is a picture on the right of the gameObject name.

\$\endgroup\$
4
\$\begingroup\$

They are hooking into the EditorApplication.hierarchyWindowItemOnGUI event. In their case they are storing a single icon texture within their editor script, and then checking the type of the object in the hierarchy, exiting the routine as soon as they've either decided there's nothing to do or they've found a specific icon to show.

I've linked to their code above (it's all open source), but something like this:

[InitializeOnLoad]
public class YourIcons : Editor
{
  static Texture2D yourIcon;
  static bool isInited = false;

  static YourIcons()
  {
    Initialize();
  }

  static void Initialize()
  {
    if (isInited)
    {
      // Only do this once.
      return;
    }

    // Find the current path we're running in
    DirectoryInfo rootDir = new DirectoryInfo(Application.dataPath);

    // Search the directory for this file
    FileInfo[] files = rootDir.GetFiles("YourIcons.cs", SearchOption.AllDirectories);

    // rework our file path into the Assets path
    string editorPath = Path.GetDirectoryName(files[0].FullName
                                .Replace("\\", "/")
                                .Replace(Application.dataPath, "Assets"));

    // Add the name of the folder with your icon
    string editorGUIPath = editorPath + "/GUI";

    // Load the icon
    yourIcon = AssetDatabase.LoadAssetAtPath<Texture2D>(editorGUIPath + "/yourIcon.png");

    EditorApplication.hierarchyWindowItemOnGUI -= HierarchyIconsOnGUI;
    EditorApplication.hierarchyWindowItemOnGUI += HierarchyIconsOnGUI;
    isInited = true;
  }

  static void HierarchyIconsOnGUI(int instanceId, Rect selectionRect)
  {
    GameObject go = (GameObject)EditorUtility.InstanceIDToObject(instanceId);

    if (!go)
    {
      // If this isn't a GameObject, then stop processing
      return;
    }

    // create a rectangle to hold the texture.
    Rect rect = new Rect(selectionRect.x - 25f, selectionRect.y + 2, 15f, 15f);

    // Check to see if the GameObject is one we care about
    if (go.GetComponent<YourComponent>())
    {
      // Position the rectangle off to the right of list, 15px in from the edge
      rect.x = selectionRect.x + selectionRect.width - 15f;
      GUI.Label(rect, yourIcon);
      return;
    }
  }
}
/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2012-2017 DragonBones team and other contributors
 *
 */
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ What part of code is doing it? If possible show the code, please. \$\endgroup\$ – cutMeDown Jan 19 '18 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.