This will hopefully cover all your folding needs
Using the Collapse
method from this answer, I was able to write the following one-liners (as you requested):
public static class Folds
{
[MenuItem("Folds/FoldSelection #&,")]
public static void FoldSelection()
{
Utils.CollapseSelection(false);
}
[MenuItem("Folds/CollapseSelection #&.")]
public static void CollapseSelection()
{
Utils.CollapseSelection(true);
}
[MenuItem("Folds/FoldAllExceptCurrentSelected %#&,")]
public static void FoldAllExceptCurrentSelected()
{
Utils.CollapseAllExcept(Selection.activeGameObject, false);
}
[MenuItem("Folds/CollapseAllExceptCurrentSelected %#&.")]
public static void CollapseAllExceptCurrentSelected()
{
Utils.CollapseAllExcept(Selection.activeGameObject, true);
}
}
And then put these in your Utility
class (just a static class) (you can tell that mine is called Utils
) (Collapse
goes there as well)
public static void CollapseSelection(bool value)
{
var selection = Selection.GetFiltered(typeof(GameObject), SelectionMode.TopLevel);
foreach(var go in selection)
Collapse(go, value);
}
public static void CollapseAllExcept(GameObject go, bool value)
{
// get the toplevel GOs (whose parents are null) - exclude 'go' - Don't forget to include System.Linq for the Where method to work
var toplevelGos = Object.FindObjectsOfType<GameObject>().Where(g => g.transform.parent == null && g != go);
foreach(var g in toplevelGos)
Collapse(g, value);
SelectObject(go);
}
REMARK:
%: Ctrl on Windows, cmd on OS X
#: Shift
&: Alt
However, all this stuff deals with GameObjects
in the Hiearchy
window, if you wanted to deal with Objects
, then this means that we could be selecting something from the Project
window (i.e. assets, folders, etc) - so our current Collapse
won’t work cause it’s using the Hierarchy
window. But it’s very simple to add that functionality to it, modify the Collapse
method to:
public static void Collapse(Object obj, bool collapse, string window = "Hierarchy") // by default, it's the "Hierarchy" window
{
// get a reference to the wanted window
var hierarchy = GetFocusedWindow(window);
// select our object
SelectObject(obj);
// create a new key event (RightArrow for collapsing, LeftArrow for folding)
var key = new Event { keyCode = collapse ? KeyCode.RightArrow : KeyCode.LeftArrow, type = EventType.keyDown };
// finally, send the event to the window
hierarchy.SendEvent(key);
}
Now you could fold/collapse stuff from the Project
window as well:
Collapse(obj, true, "Project");