Skip to content

Instantly share code, notes, and snippets.

@Volantk
Created January 15, 2021 08:22
Show Gist options
  • Save Volantk/e17b722d1f0822a9641941ecfadf12ad to your computer and use it in GitHub Desktop.
Save Volantk/e17b722d1f0822a9641941ecfadf12ad to your computer and use it in GitHub Desktop.
Unity function for sorting objects by their position in the hierarchy.
public static IEnumerable<T> OrderByPositionInHierarchy<T>(this IEnumerable<T> enumerable) where T : Component
{
return enumerable.OrderBy(comp => new HierarchySortable(comp.gameObject));
}
/// <summary>
/// Sorts a list of gameobjects by their position in the hierarchy (top to bottom as if the entire hierarchy is expanded)
/// Example: sortedGameobjects = unsortedGameobjects.OrderBy(go => new HierarchySortable(go)).ToList();
/// </summary>
public struct HierarchySortable : IComparable<HierarchySortable>
{
private List<int> _parentSiblingIndexes;
public HierarchySortable(GameObject gameObject) : this()
{
_parentSiblingIndexes = new List<int>();
if (gameObject.transform.parent == null)
{
_parentSiblingIndexes.Add(gameObject.transform.GetSiblingIndex());
}
else
{
Transform parent = gameObject.transform;
while (parent)
{
_parentSiblingIndexes.Add(parent.GetSiblingIndex());
parent = parent.parent;
}
}
_parentSiblingIndexes.Reverse();
}
public int CompareTo(HierarchySortable other)
{
int aCount = this._parentSiblingIndexes.Count;
int bCount = other._parentSiblingIndexes.Count;
for (int i = 0; i < Math.Max(bCount, aCount); i++)
{
bool aMaxed = i >= aCount;
bool bMaxed = i >= bCount;
if (aMaxed && !bMaxed)
return -1;
else if (!aMaxed && bMaxed)
return 1;
int a = this._parentSiblingIndexes[i];
int b = other._parentSiblingIndexes[i];
if (a > b)
return 1;
else if (a < b)
return -1;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment