Devlog: Reorder Unity Components Automatically

Here’s a little editor script that reorders components on GameObjects to be in a fixed order (scripts use alphabetical base class before MonoBehaviour).

I have only tested this on Unity 4.6.  If you are running another version, please verify that the script works in the comment section.

Note that I have opted to skip all camera-bearing GameObjects as they can posses MonoBehaviours that call OnRenderImage, which is an order-dependent method.

Performance

To minimize any performance costs of polling, I decided that reordering need only take place when a new GameObject is selected. Adding new components, removing components, or moving components, will not immediately be reordered; you’ll have to change selection targets.

Support

Not all component types are supported by default, as there are simply too many across the various versions of Unity, not to mention any that you might have created yourself. But unknown types will elicit a Debug Warning to remind you to add them in.

Order

Order is handled by specifying the priority (integer) value for each component type. Ties are then handled alphabetically according to the type name. Here’s what the order method looks like. You’ll want to add support for your own (Component) types here:

  private static int? GetOrder(Component component)
 {
 // physics
 if (component is Collider) return 100;
 if (component is Rigidbody) return 101;
 if (component is Joint) return 102;

 // renderers
 if (component is MeshFilter) return 200;
 if (component is Projector) return 201;
 if (component is Renderer) return 202;
 if (component is Animation) return 203;

 // lights
 if (component is Light) return 300;

 // nav mesh
 if (component is NavMeshAgent) return 400;
 if (component is NavMeshObstacle) return 401;

 // particles
 if (component is ParticleSystem) return 500;

 // environment
 if (component is Tree) return 600;

 // scripts
 if (component is MonoBehaviour)
 {
 int order = 1000;

 // custom script ordering goes here
 // if (component is SpeciallyOrderedMonoBehaviourSubclass) order += 1;

 return order;
 }

 // warning
 Debug.LogWarning("Force Component Order: " + component.GetType().Name + " component is not supported.");
 return null;
 }

Downloads

Update!

The above code works, but for complex scenes will cause the editor to hitch when selecting or de-selecting prefab instances that have colliders and several copies in the scene. I’ve made some minor changes to the script that push it into the Transform component’s context menu rather than executing all the time. You can find my updated source here: http://pastebin.com/37fDAnh4

One thought on “Devlog: Reorder Unity Components Automatically”

Comments are closed.