Search Unity

Creating a new Mecanim parameter from code

Discussion in 'Scripting' started by DavidDebnar, Dec 23, 2015.

  1. DavidDebnar

    DavidDebnar

    Joined:
    Mar 19, 2011
    Posts:
    115
    Hello!

    Is anyone aware if it's possible to create new parameters for a Mecanim animation controller from code? Either by using an Editor script, or even better at runtime.

    Thanks,
    David
     
  2. DavidDebnar

    DavidDebnar

    Joined:
    Mar 19, 2011
    Posts:
    115
    Ok, I solved it. The key is to cast the Runtime Animation Controller the Animator class provides to an AnimationController and then it's easy to add new parameters using the .AddParameter method.

    (only possible in the Editor, because it uses UnityEditor.Animations)

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor.Animations;
    3.  
    4. public class ParameterTest : MonoBehaviour
    5. {
    6.     protected void AddParameter ()
    7.     {
    8.         // We first need to get the animator attached to this object
    9.         // and then cast it's runtimeAnimationController
    10.         // to an AnimationController
    11.         Animator animator = GetComponent<Animator> ();
    12.         AnimatorController animatorController = (AnimatorController) animator.runtimeAnimatorController;
    13.  
    14.         // Method 1, keeps reference to the parameter
    15.  
    16.         AnimatorControllerParameter parameter = new AnimatorControllerParameter ();
    17.         parameter.type = AnimatorControllerParameterType.Bool;
    18.         parameter.name = "NewParameter1";
    19.  
    20.         animatorController.AddParameter (parameter);
    21.  
    22.         // Method 2, shorter, but without a reference
    23.  
    24.         animatorController.AddParameter ("NewParameter2", AnimatorControllerParameterType.Float);
    25.     }
    26. }
     
    Last edited: Dec 23, 2015