Skip to content

Instantly share code, notes, and snippets.

@yasirkula
Last active June 4, 2026 04:39
Show Gist options
  • Select an option

  • Save yasirkula/0b541b0865eba11b55518ead45fba8fc to your computer and use it in GitHub Desktop.

Select an option

Save yasirkula/0b541b0865eba11b55518ead45fba8fc to your computer and use it in GitHub Desktop.
An editor script for Unity 3D to collapse all GameObject's in Hierarchy view or to collapse all folders in Project view. See the comments section below for instructions.
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEditorInternal;
using UnityEngine.SceneManagement;
#if UNITY_6000_3_OR_NEWER
using EntityId = UnityEngine.EntityId;
#else
using EntityId = System.Int32;
#endif
#if UNITY_6000_3_OR_NEWER
using TreeViewItem = UnityEditor.IMGUI.Controls.TreeViewItem<UnityEngine.EntityId>;
using TreeViewState = UnityEditor.IMGUI.Controls.TreeViewState<UnityEngine.EntityId>;
#elif UNITY_6000_2_OR_NEWER
using TreeViewItem = UnityEditor.IMGUI.Controls.TreeViewItem<int>;
using TreeViewState = UnityEditor.IMGUI.Controls.TreeViewState<int>;
#endif
public static class EditorCollapseAll
{
private const BindingFlags INSTANCE_FLAGS = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
private const BindingFlags STATIC_FLAGS = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
[MenuItem( "Assets/Collapse All", priority = 1000 )]
private static void CollapseFolders()
{
EditorWindow projectWindow = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.ProjectBrowser" ).GetField( "s_LastInteractedProjectBrowser", STATIC_FLAGS ).GetValue( null ) as EditorWindow;
if( projectWindow )
{
object assetTree = projectWindow.GetType().GetField( "m_AssetTree", INSTANCE_FLAGS ).GetValue( projectWindow );
if( assetTree != null )
CollapseTreeViewController( projectWindow, assetTree, (TreeViewState) projectWindow.GetType().GetField( "m_AssetTreeState", INSTANCE_FLAGS ).GetValue( projectWindow ) );
object folderTree = projectWindow.GetType().GetField( "m_FolderTree", INSTANCE_FLAGS ).GetValue( projectWindow );
if( folderTree != null )
{
object treeViewDataSource = folderTree.GetType().GetProperty( "data", INSTANCE_FLAGS ).GetValue( folderTree, null );
#if UNITY_6000_5_OR_NEWER
object singletonFavoritesEntityIds = typeof(EditorWindow).Assembly.GetType("UnityEditor.FavoritesEntityIds").BaseType.GetProperty("instance", STATIC_FLAGS).GetValue(null, null);
MethodInfo filterIdToEntityIdRemapper = singletonFavoritesEntityIds.GetType().GetMethod("GetOrAllocateEntityIdFor", INSTANCE_FLAGS);
int searchFiltersRootFilterID = (int)typeof(EditorWindow).Assembly.GetType("UnityEditor.SavedSearchFilters").GetMethod("GetRootFilterId", STATIC_FLAGS).Invoke(null, null);
EntityId searchFiltersRootEntityID = (EntityId)filterIdToEntityIdRemapper.Invoke(singletonFavoritesEntityIds, new object[] { searchFiltersRootFilterID });
#else
int searchFiltersRootInstanceID = (int)typeof(EditorWindow).Assembly.GetType("UnityEditor.SavedSearchFilters").GetMethod("GetRootInstanceID", STATIC_FLAGS).Invoke(null, null);
#pragma warning disable CS0618 // Type or member is obsolete
EntityId searchFiltersRootEntityID = searchFiltersRootInstanceID;
#pragma warning restore CS0618 // Type or member is obsolete
#endif
bool isSearchFilterRootExpanded = (bool)treeViewDataSource.GetType().GetMethod("IsExpanded", INSTANCE_FLAGS, null, new System.Type[] { typeof(EntityId) }, null).Invoke(treeViewDataSource, new object[] { searchFiltersRootEntityID });
CollapseTreeViewController(projectWindow, folderTree, (TreeViewState)projectWindow.GetType().GetField("m_FolderTreeState", INSTANCE_FLAGS).GetValue(projectWindow), isSearchFilterRootExpanded ? new EntityId[1] { searchFiltersRootEntityID } : null);
// Preserve Assets and Packages folders' expanded states because they aren't automatically preserved inside ProjectBrowserColumnOneTreeViewDataSource.SetExpandedIDs
// https://github.com/Unity-Technologies/UnityCsReference/blob/e740821767d2290238ea7954457333f06e952bad/Editor/Mono/ProjectBrowserColumnOne.cs#L408-L420
#if UNITY_6000_3_OR_NEWER
InternalEditorUtility.expandedProjectWindowItemIds = (EntityId[])treeViewDataSource.GetType().GetMethod("GetExpandedIDs", INSTANCE_FLAGS).Invoke(treeViewDataSource, null);
#else
InternalEditorUtility.expandedProjectWindowItems = (int[])treeViewDataSource.GetType().GetMethod("GetExpandedIDs", INSTANCE_FLAGS).Invoke(treeViewDataSource, null);
#endif
TreeViewItem rootItem = (TreeViewItem) treeViewDataSource.GetType().GetField( "m_RootItem", INSTANCE_FLAGS ).GetValue( treeViewDataSource );
if( rootItem.hasChildren )
{
foreach (TreeViewItem item in rootItem.children)
EditorPrefs.SetBool("ProjectBrowser" + item.displayName, (bool)treeViewDataSource.GetType().GetMethod("IsExpanded", INSTANCE_FLAGS, null, new System.Type[] { typeof(EntityId) }, null).Invoke(treeViewDataSource, new object[] { item.id }));
}
}
}
}
[MenuItem( "GameObject/Collapse All", priority = 40 )]
private static void CollapseGameObjects( MenuCommand command )
{
// This happens when this button is clicked while multiple Objects were selected. In this case,
// this function will be called once for each selected Object. We don't want that, we want
// the function to be called only once
if( command.context )
{
EditorApplication.update -= CallCollapseGameObjectsOnce;
EditorApplication.update += CallCollapseGameObjectsOnce;
return;
}
EditorWindow hierarchyWindow = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.SceneHierarchyWindow" ).GetField( "s_LastInteractedHierarchy", STATIC_FLAGS ).GetValue( null ) as EditorWindow;
if( hierarchyWindow )
{
object hierarchyTreeOwner = hierarchyWindow.GetType().GetField( "m_SceneHierarchy", INSTANCE_FLAGS ).GetValue( hierarchyWindow );
object hierarchyTree = hierarchyTreeOwner.GetType().GetField( "m_TreeView", INSTANCE_FLAGS ).GetValue( hierarchyTreeOwner );
if( hierarchyTree != null )
{
List<EntityId> expandedSceneIDs = new(4);
foreach( string expandedSceneName in (IEnumerable<string>) hierarchyTreeOwner.GetType().GetMethod( "GetExpandedSceneNames", INSTANCE_FLAGS ).Invoke( hierarchyTreeOwner, null ) )
{
Scene scene = SceneManager.GetSceneByName( expandedSceneName );
if (scene.IsValid())
#if UNITY_6000_3_OR_NEWER
expandedSceneIDs.Add((EntityId)typeof(SceneHandle).GetMethod("ToEntityId", INSTANCE_FLAGS).Invoke(scene.handle, null)); // SceneHandle's EntityId is used by SceneHierarchyWindow
#else
expandedSceneIDs.Add(scene.GetHashCode()); // GetHashCode returns m_Handle which in turn is used as the Scene's instanceID by SceneHierarchyWindow
#endif
}
CollapseTreeViewController( hierarchyWindow, hierarchyTree, (TreeViewState) hierarchyTreeOwner.GetType().GetField( "m_TreeViewState", INSTANCE_FLAGS ).GetValue( hierarchyTreeOwner ), expandedSceneIDs );
}
}
}
private static void CallCollapseGameObjectsOnce()
{
EditorApplication.update -= CallCollapseGameObjectsOnce;
CollapseGameObjects( new MenuCommand( null ) );
}
private static void CollapseTreeViewController(EditorWindow editorWindow, object treeViewController, TreeViewState treeViewState, IList<EntityId> additionalInstanceIDsToExpand = null)
{
object treeViewDataSource = treeViewController.GetType().GetProperty( "data", INSTANCE_FLAGS ).GetValue( treeViewController, null );
List<EntityId> treeViewSelectedIDs = new(treeViewState.selectedIDs);
EntityId[] additionalInstanceIDsToExpandArray;
if (additionalInstanceIDsToExpand != null && additionalInstanceIDsToExpand.Count > 0)
{
treeViewSelectedIDs.AddRange(additionalInstanceIDsToExpand);
additionalInstanceIDsToExpandArray = new EntityId[additionalInstanceIDsToExpand.Count];
additionalInstanceIDsToExpand.CopyTo(additionalInstanceIDsToExpandArray, 0);
}
else
additionalInstanceIDsToExpandArray = new EntityId[0];
treeViewDataSource.GetType().GetMethod( "SetExpandedIDs", INSTANCE_FLAGS ).Invoke( treeViewDataSource, new object[] { additionalInstanceIDsToExpandArray } );
treeViewDataSource.GetType().GetMethod( "RevealItems", INSTANCE_FLAGS ).Invoke( treeViewDataSource, new object[] { treeViewSelectedIDs.ToArray() } );
editorWindow.Repaint();
}
[MenuItem( "CONTEXT/Component/Collapse All", priority = 1400 )]
private static void CollapseComponents( MenuCommand command )
{
// Credit: https://forum.unity.com/threads/is-it-possible-to-fold-a-component-from-script-inspector-view.296333/#post-2353538
ActiveEditorTracker tracker = ActiveEditorTracker.sharedTracker;
for( int i = 0, length = tracker.activeEditors.Length; i < length; i++ )
tracker.SetVisible( i, 0 );
EditorWindow.focusedWindow.Repaint();
}
}
@yasirkula

yasirkula commented Oct 29, 2017

Copy link
Copy Markdown
Author

How To
Just put it in Assets/Editor folder of your project.

Collapsing Hierarchy View
To collapse all GameObjects in the currently active Hierarchy window, either use the GameObject menu or right click a GameObject and select "Collapse All". Note that parent GameObjects containing the selected GameObjects will not be collapsed.

Collapsing Project View
To collapse all folders in Project window, either use the Assets menu or right click an asset and select "Collapse All". Note that folders containing the selected assets will not be collapsed.

Collapsing Components
To collapse all components in the Inspector window, right click a component and select "Collapse All".

EditorCollapseAll

@peteski

peteski commented May 29, 2018

Copy link
Copy Markdown

Hey this is cool! Thankyou!
I combined it with this to have collapse on components also. https://forum.unity.com/threads/expand-collapse-all-components-in-a-gameobject-refresh-issue.517866/#post-3471049

@aybe

aybe commented Jan 21, 2019

Copy link
Copy Markdown

FYI the same functionality is achieved by simply holding Alt when clicking a foldout 😃

@netlander

Copy link
Copy Markdown

That's right Alt + LMB on the disclosing arrow achieves the exact same thing. Came here 'cause I'm looking for collapse all components in inspector.

@yasirkula

Copy link
Copy Markdown
Author

Added! Simply right click a component and select "Collapse All".

@netlander

netlander commented Jan 23, 2020

Copy link
Copy Markdown

Tried using the updated code just now and Inspector Collapse All does not work, at least not on Unity 2018.4.0f1

Edit: It has started working after a little while ( after restarting Unity I think). But there is still a problem: When navigating away and back from a collapsed game object the inspector shows the object expanded, in other words it does not seem to remember the collapsed state of the object.

Is there any way to fix this issue?

@yasirkula

Copy link
Copy Markdown
Author

You can add this code to the top of CollapseComponents function:

if( Selection.activeGameObject )
{
	foreach( Component component in Selection.activeGameObject.GetComponents<Component>() )
		UnityEditorInternal.InternalEditorUtility.SetIsInspectorExpanded( component, false );
}

But be aware that this will affect that component type (e.g. Transform) on ALL objects. There is no way to set the collapsed state of a component permanantly object-wise.

@netlander

Copy link
Copy Markdown

Not ideal but I might give it a try. Thanks very much.

@thautwarm

Copy link
Copy Markdown

thank you

@milox

milox commented May 4, 2022

Copy link
Copy Markdown

Doesn't work anymore, just switches focus to Packages folder. But Unity does seem to have this function natively now, using Alt + click on the Assets folder.

@yasirkula

Copy link
Copy Markdown
Author

@milox On which Unity version did it not work as intended?

@milox

milox commented May 5, 2022

Copy link
Copy Markdown

@milox On which Unity version did it not work as intended?

2020.3.33 and 2021.3.0

@yasirkula

Copy link
Copy Markdown
Author

I unfortunately couldn't reproduce the issue on 2021.3.0f1:

Recording

@milox

milox commented May 5, 2022

Copy link
Copy Markdown

Well, I get this
ezgif com-gif-maker

@yasirkula

Copy link
Copy Markdown
Author

@milox I haven't tried it in Two Column Layout before, you're right. I've now fixed the issue. It also works much smoother now ^^

@milox

milox commented May 7, 2022

Copy link
Copy Markdown

@yasirkula Nice, thanks

@WildRikku

Copy link
Copy Markdown

Hey, thank you, very useful. I will try to adjust this to do what I long wished for, a "collapse all but one" functionality for components.

@yasirkula

Copy link
Copy Markdown
Author

@WildRikku You can modify CollapseComponents to achieve that. The right clicked component is stored in command.context.

@hegworks

hegworks commented Sep 3, 2023

Copy link
Copy Markdown

great script! got my star ❤️
is there any way to implement such option for when exporting a unity package?
it is very annoying when exporting something, unity selects all the assets imported automatically and unselecting them one by one is a nuisance.

@yasirkula

Copy link
Copy Markdown
Author

@hegworks Thanks! In the export window, deselecting "Include dependencies" should do the trick.

@MasashiWada

Copy link
Copy Markdown

I appreciate your long-term contributions.
When I saw the build issue in Unity 6.3, I was trying to fix it myself, but I'm glad you managed to resolve it.

@yasirkula

Copy link
Copy Markdown
Author

@MasashiWada Glad to hear it! Feel free to notify me when there are incompatibilities with newer versions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment