Skip to content

Instantly share code, notes, and snippets.

@skjalgsm
Forked from AngryAnt/MoveComponentContext.cs
Created October 24, 2016 08:41
Show Gist options
  • Save skjalgsm/8aeb1c947e4a50c2cbf46877fd2edce4 to your computer and use it in GitHub Desktop.
Save skjalgsm/8aeb1c947e4a50c2cbf46877fd2edce4 to your computer and use it in GitHub Desktop.
Adds "Move to Top" and "Move to Bottom" items to the inspector context menu of components.
using UnityEngine;
using UnityEditor;
namespace Agens.Editor
{
public static class MoveComponentContext
{
internal enum Destination
{
Top,
Bottom
}
private const string ComponentArrayName = "m_Component";
private const int FirstComponentIndex = 1;
[MenuItem("CONTEXT/Component/Move to Top")]
public static void Top(MenuCommand command)
{
Move(command.context, Destination.Top);
}
[MenuItem("CONTEXT/Component/Move to Bottom")]
public static void Bottom(MenuCommand command)
{
Move(command.context, Destination.Bottom);
}
private static void Move(Object target, Destination destination)
{
var component = target as Component;
if (component == null)
{
Debug.LogWarning("Cant move " + target + " to " + destination, target);
return;
}
var serializedObject = new SerializedObject(component.gameObject);
var componentArray = serializedObject.FindProperty(ComponentArrayName);
var lastComponentIndex = componentArray.arraySize - 1;
var targetIndex = destination == Destination.Top ? FirstComponentIndex : lastComponentIndex;
for (int index = FirstComponentIndex; index <= lastComponentIndex; ++index)
{
var iterator = componentArray.GetArrayElementAtIndex(index);
iterator.Next(true);
iterator.Next(true);
if (iterator.objectReferenceValue == target)
{
componentArray.MoveArrayElement(index, targetIndex);
serializedObject.ApplyModifiedProperties();
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment