Thursday, September 5, 2013

Unity Helper Methods #1: Animator.SetLayerWeights

/// <summary>
/// Sets the weight of all the layers in the specified Animator
/// </summary>
/// <param name="animator">The animator</param>
/// <param name="totalLayers">The number of layers this animator contains</param>
/// <param name="weight">The value of the weight</param>
public static void SetLayerWeights(this Animator animator, int totalLayers, float weight)
    for (int i = 0; i < totalLayers; i++)
        animator.SetLayerWeight(i + 1, weight);


Starting with a fairly trivial method; setting the weight of 'all' the layers of an Animator. When a game starts, Unity by default sets all the layers of the Animators' Controllers to 0.

Unfortunately, the method needs to be supplied with the number of layers that the Animator contains because I haven't yet found a way how to get the number of layers programmatically.

Typical Usage

I use this method at the start of a game to set the weight of all the layers to 1.

So, if I know that I have 4 layers for a particular Animator:
animator.SetLayerWeights(4, 1); // Sets the weight of all (4) the layers of my animator