frideal
8/4/2015 - 4:10 PM

Adds "Move to Top" and "Move to Bottom" items to the inspector context menu of components.

Adds "Move to Top" and "Move to Bottom" items to the inspector context menu of components. UnityEditorInternal.ComponentUtility 也能实现该功能......

using UnityEngine;
using UnityEditor;


public class MoveComponentContext
{
	enum Destination
	{
		Top,
		Bottom
	};


	const string kComponentArrayName = "m_Component";
	const int kFirstComponentIndex = 1;


	[MenuItem ("CONTEXT/Component/Move to Top")]
	static void Top (MenuCommand command)
	{
		Move ((Component)command.context, Destination.Top);
	}


	[MenuItem ("CONTEXT/Component/Move to Bottom")]
	static void Bottom (MenuCommand command)
	{
		Move ((Component)command.context, Destination.Bottom);
	}


	static void Move (Component target, Destination destination)
	{
		SerializedObject gameObject = new SerializedObject (target.gameObject);
		SerializedProperty componentArray = gameObject.FindProperty (kComponentArrayName);

		int lastComponentIndex = componentArray.arraySize - 1;
		int targetIndex = destination == Destination.Top ? kFirstComponentIndex : lastComponentIndex;

		for (int index = kFirstComponentIndex; index <= lastComponentIndex; ++index)
		{
			SerializedProperty iterator = componentArray.GetArrayElementAtIndex (index);
			iterator.Next (true);
			iterator.Next (true);

			if (iterator.objectReferenceValue == target)
			{
				componentArray.MoveArrayElement (index, targetIndex);
				gameObject.ApplyModifiedProperties ();

				break;
			}
		}
	}
}