目的
在Hierarchy视图中将所有挂有自定义脚本组件的游戏对象标记出来,如下图所示:所有挂有自定义脚本组件的游戏对象名称后面都有一个脚本图标。
image.png
用法
将下面的代码文件放在工程中的Editor目录下。
代码
FanShowMonoBehaviourInHierarchy.cs
using System.Net.Mime;
using System.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class FanShowMonoBehaviourInHierarchy
{
public static bool EnableShowMonoBehaviourInHierarchy = true;
public static bool ShouldModifyNameColor = false;
public static bool ShouldShowIcon = true;
public static Color TargetColor
{
get
{
return new Color(200/255f, 200/255f, 50/255f, 1f);
}
}
static FanShowMonoBehaviourInHierarchy()
{
EditorApplication.hierarchyWindowItemOnGUI += ShowMonoBehaviourInHierarchy;
}
private static void ShowMonoBehaviourInHierarchy(int instanceId, Rect selectionRect)
{
if(!EnableShowMonoBehaviourInHierarchy)
{
return;
}
try
{
var rectCheck = new Rect(selectionRect);
rectCheck.x += rectCheck.width - 20;
rectCheck.width = 18;
var obj = EditorUtility.InstanceIDToObject(instanceId);
var go = (GameObject)obj;
var color = TargetColor;
if (!go.activeInHierarchy)
{
color.a = 0.5f;
}
var index = 0;
GUIStyle style = null;
if (ShouldModifyNameColor)
{
ModifyColor<MonoBehaviour>(selectionRect, go, color, ref index, ref style);
}
if (ShouldShowIcon)
{
DrawRectIcon<MonoBehaviour>(selectionRect, go, ref index, ref style);
}
if (style != null)
{
GUI.Label(selectionRect, go.name, style);
}
}
catch(Exception)
{}
}
private static void ModifyColor<T>(Rect selectionRect, GameObject go, Color textColor,
ref int order, ref GUIStyle style)where T:Component
{
if(go.HasComponent<T>(false))
{
if (EnableShowMonoBehaviourInHierarchy)
{
style = LabelStyle(textColor);
}
}
}
private static void DrawIcon<T>(Rect rect)
{
var icon = EditorGUIUtility.IconContent("cs Script Icon");
GUI.Label(rect, icon);
}
private static Rect CreateRect(Rect selectionRect, int index)
{
var rect = new Rect(selectionRect);
rect.x += rect.width - 20 - (20 * index);
rect.width = 18;
return rect;
}
private static void DrawRectIcon<T>(Rect selectionRect, GameObject go, ref int order,
ref GUIStyle style) where T:Component
{
if (go.HasComponent<T>(false))
{
order += 1;
var rect = CreateRect(selectionRect, order);
DrawIcon<T>(rect);
}
}
private static GUIStyle LabelStyle(Color color)
{
var style = new GUIStyle(((GUIStyle)"Label"))
{
padding =
{
left = EditorStyles.label.padding.left + 17,
top = EditorStyles.label.padding.top - 3
},
normal =
{
textColor = color
}
};
return style;
}
}
public static class ExtensionMethods
{
public static bool HasComponent<T>(this GameObject go, bool checkChildren)where T:Component
{
T temp = null;
if (!checkChildren)
{
temp = go.GetComponent<T>();
}
else
{
temp = go.GetComponentsInChildren<T>().FirstOrDefault();
}
return temp != null && !(temp is UnityEngine.EventSystems.UIBehaviour);
}
}
网友评论