Search Unity

Modify AnimatorController through script and save it?

Discussion in 'Scripting' started by teighshiclbw, Jan 17, 2019.

  1. teighshiclbw

    teighshiclbw

    Joined:
    Jun 26, 2018
    Posts:
    34
    Here's script:
    Code (CSharp):
    1.     [MenuItem("Tools/ModifyAnimator")]
    2.     static void ModifyAnimator()
    3.     {
    4.         foreach (Object o in Selection.objects)
    5.         {
    6.             AnimatorController animatorController = o as AnimatorController;
    7.  
    8.             for (int i = 0; i < animatorController.layers[0].stateMachine.states.Length; i++)
    9.             {
    10.                 if (animatorController.layers[0].stateMachine.states[i].state.name == "State1")
    11.                 {
    12.                     AnimatorStateTransition newTransition = new AnimatorStateTransition();
    13.                     newTransition.destinationState = animatorController.layers[0].stateMachine.states[1].state;
    14.                     animatorController.layers[0].stateMachine.states[i].state.AddTransition(newTransition);
    15.                 }
    16.             }
    17.  
    18.             EditorUtility.SetDirty(animatorController);
    19.             AssetDatabase.SaveAssets();
    20.         }
    21.     }
    It load a AnimatorController from selection and found state1 and add transition to state2, then save this AnimatorController.
    Very simple.


    These code add transition succesfully, animator window shows it, and it actually work in game, so far so good.
    But if I close Unity and open unity again, the transition disappear,AnimatorController not modify at all.

    How can I save modified AnimatorController through script?