Gets the VisualElement that displays the icon of the item. Add a USS class to this element to display a custom icon for the item type.
The following example changes the icon a GameObject uses in the Hierarchy window if it has a specified tag. It uses Icon to add a custom USS class to the icon element of items whose GameObject has the Favorite tag.
The example requires a USS file called ChangeNodeIcon.uss and a tag called Favorite.
To use this example:
Assets/Editor/ChangeNodeIcon. Scripts in an Editor folder can use the Hierarchy module API without additional setup. If you save the script outside of an Editor folder, you must enable the Hierarchy built-in module in the Package Manager window, which also adds the module to your Player builds.ChangeNodeIcon.uss in the same Assets/Editor/ChangeNodeIcon folder.Favorite: select a GameObject, open the Tag dropdown in the Inspector window, and select Add Tag.Favorite tag to a GameObject to change the icon it displays.using Unity.Hierarchy; using Unity.Hierarchy.Editor; using UnityEditor; using UnityEngine; using UnityEngine.UIElements;
namespace Unity.HierarchySamples.Editor { class ChangeNodeIcon { const string k_FavoriteUssClass = "gameobject--favorite";
[InitializeOnLoadMethod] static void Initialize() { HierarchyWindow.BindView += OnBindView; HierarchyWindow.BindViewItem += OnBindViewItem; }
static void OnBindView(HierarchyWindow window, HierarchyView view) { view.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Editor/ChangeNodeIcon/ChangeNodeIcon.uss")); }
static void OnBindViewItem(HierarchyWindow window, HierarchyView view, HierarchyViewItem item) { if (item.Handler is not HierarchyGameObjectHandler handler) return;
GameObject gameObject = handler.GetGameObject(item.Node); if (gameObject == null) return;
// CompareTag throws an error if the 'Favorite' tag isn't defined in the project. // To define the 'Favorite' tag, select a GameObject, open the Tag dropdown in the Inspector window, select Add Tag, and create a new tag called 'Favorite'. if (System.Array.IndexOf(UnityEditorInternal.InternalEditorUtility.tags, "Favorite") < 0) return;
bool isFavorite = gameObject.CompareTag("Favorite"); item.Icon.EnableInClassList(k_FavoriteUssClass, isFavorite); // Inline styling needs to be cleared to show custom USS icon. if (isFavorite) item.Icon.style.backgroundImage = StyleKeyword.Null; } } }
The following example shows how to style ChangeNodeIcon.uss.
.hierarchy-item__icon.gameobject--favorite {
background-image: resource("Icons/Favorite_colored.png");
}
.unity-collection-view__item--selected:hover:enabled .hierarchy-itemicon.gameobject--favorite,
.unity-collection-view:focus .unity-collection-viewitem--selected .hierarchy-itemicon.gameobject--favorite {
background-image: resource("Icons/Favorite_colored.png");
}