I'm extremely new to extending the Unity editor, and pieced together this script that highlights the selected object in the hierarchy. The problem is, when I'm in the editor and the top of the stack(scene name) comes into view on the tree, the whole hierarchy turns invisible! When I scroll down so the scene name goes out of view it fixes itself. I've attached images to give you a better idea of whats happening. This problem is minor when I have a bunch of objects, but would be unusable on a new scene.
[InitializeOnLoad]
public class HierarchyHighlighter
{
static HierarchyHighlighter()
{
EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItem_CB;
}
private static void HierarchyWindowItem_CB(int selectionID, Rect selectionRect)
{
Object o = EditorUtility.InstanceIDToObject(selectionID);
if ((o as GameObject).GetComponent<HierarchyHighlighterComponent>() != null)
{
HierarchyHighlighterComponent h = (o as GameObject).GetComponent<HierarchyHighlighterComponent>();
if (h.highlight)
{
if (Event.current.type == EventType.Repaint)
{
GUI.backgroundColor = h.color;
GUI.Box(selectionRect, "");
GUI.backgroundColor = Color.white;
EditorApplication.RepaintHierarchyWindow();
}
}
}
}
}
The console reads: "Object reference not set to an instance of an object" HierarchyHighlighter.HierarchyWindowItem_CB(Int32 selectionID, Rect selectionRect) (at Assets/HierarchyHighlighter.cs:18)
Images: Functioning as normal
Thank you for your help!
Your code is throwing a null reference exception. I don't know which line is 18 because it's probably different in the file from what you posted, but my guess would be that Object o = EditorUtility...
is returning null or that the object it returns isn't a GameObject so (o as GameObject)
returns null and throws the exception when you call GetComponent.
There are also three obvious optimisations you could make:
(o as GameObject)
cast once. You don't even need o as an Object at all, so you could do the cast as soon as you get it: GameObject o = EditorUtility.InstanceIDToObject(selectionID) as GameObject;
(then null check o to fix the exception)....Component h = o.GetComponent...
, then if (h != null && h.highlight)
.if (Event.current.type == EventType.Repaint)
to the start of the function, otherwise you're wasting all this performance on every other gui event.Also, use descriptive variable names. obj and highlighter would be much better than o and h.