How to animate the render order of objects in the new Unity3D 4.6 uGUI

I want to animate a GUI element behind something during part of the animation and in front of it for the rest. The render order of GUI items is the order they appear in the hierarchy window, so how do we change that in an animation?

I could not find a built in way to do this so resorted to writing a script, (Please let me know if you know a built in way). In script you can use the Transform.SetSiblingIndex() function to set the child index of a transform.

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class UtilsAnimateHierarchyOrder : MonoBehaviour {

    public float siblingOrder;
    void Awake ()
    {
        siblingOrder = transform.GetSiblingIndex();
    }

    void OnValidate()
    {
        siblingOrder = Mathf.Round(siblingOrder);
        if (siblingOrder != transform.GetSiblingIndex())
        {
            transform.SetSiblingIndex((int)siblingOrder);
            siblingOrder = transform.GetSiblingIndex();
        }
    }

    void OnDidApplyAnimationProperties ()
    {
        OnValidate();
    }
}

The script makes use of a couple of useful functions. OnValidate() gets called whenever unity modifies the serialized fields in your class, except for some reason when the animation system changes a value. When this occurs a currently undocumented function is called OnDidApplyAnimationProperties(), the internals of the new GUI make use of this call, so hopefully when it goes open source we this function will gain documentation.

Also essential in making the above script work when creating an animation is the following tag:

[ExecuteInEditMode]

which does exactly what it says on the tin.

I hope this is useful for someone out there, note that if you want to animate multiple transforms then the order in which you SetSiblingIndex is important, as such the above approach is unlikely to work but may be a good starting point. In my scenario I only needed to edit the relative position of one item so the above sufficed.

Leave a Reply