How to change/update hierachy panel's sorting algorithm by code?

I have couple of my own sorting algorithm for ordering game objects in the hierarchy panel. The sorting algorithms are implemented by deriving the BaseHierarchySort class. I can change the hierarchy panel’s sorting algorithm manually on the top right corner of the panel. Is it possible or How to do the same by using code? And I also want to know how ask the hierarchy panel to resort ordering of game objects in code.

Well, Unity doesn’t provide a public API for that. However you can of course use reflection :wink:

edit

I removed my original answer since it was actually wrong since i accidentally looked at an older Unity version ^^. In the current version it’s much simpler. The “SceneHierarchyWindow” class now has a public method called “SetSortFunction” which let you pass a Type object of your desired sorting “object”.

Since “SceneHierarchyWindow” is an internal type we can only use reflection to access it.

using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Reflection;


public class HierarchyHelper
{
    private static System.Type m_HWType = null;
    private static System.Reflection.MethodInfo m_SetSortFunction;

    public static void SetHierarchySortFunction(System.Type aType)
    {
        if (m_HWType == null)
        {
            m_HWType = typeof(EditorWindow).Assembly.GetTypes().FirstOrDefault(t => t.Name == "SceneHierarchyWindow");
            if (m_HWType == null)
                throw new System.NotSupportedException("the type 'SceneHierarchyWindow' could not be found");
            m_SetSortFunction = m_HWType.GetMethod("SetSortFunction", BindingFlags.Public | BindingFlags.Instance);
            if (m_SetSortFunction == null)
                throw new System.NotSupportedException("the method 'SetSortFunction' could not be found in 'SceneHierarchyWindow'");
        }
        EditorWindow hWindow = EditorWindow.GetWindow(m_HWType);
        m_SetSortFunction.Invoke(hWindow, new object[] { aType });
    }
    public static void SetHierarchySortFunction<T>() where T : BaseHierarchySort
    {
        SetHierarchySortFunction(typeof(T));
    }
}

You can use it like this:

HierarchyHelper.SetHierarchySortFunction<YourSortingClass>();

or

HierarchyHelper.SetHierarchySortFunction(typeof(YourSortingClass));

Note: Unity also has a private overload of it’s “SetSortFunction” method which takes the type name as string. That method is actually called by the public overload. It only uses type.Name and pass on the type name internally. If you want to specify the sort function via it’s type name, you can also use the private method. For that you would need BindingFlags.NonPublic. Also keep in mind that it takes a string as argument and not a Type.