kkl
kkl

Reputation: 153

Change motion using script in Unity Editor

Hi how do we change motion in an AnimatorController using script in Unity Editor?

The red highlight is the one I'd like to change, but using script enter image description here

enter image description here

Upvotes: 4

Views: 6757

Answers (1)

derHugo
derHugo

Reputation: 90833

Changing the AnimatorController via editor scripts is always quite tricky!

  • First of all you need to have your AnimationClip from somewhere

    // somewhere get the AnimationClip from
    var clip = new AnimationClip();
    
  • Then you will have to cast the runtimeAnimatorController to an AnimatorController which is only available in the Editor! (put using UnityEditor; at the top of the script!)

    var controller = (AnimatorController)animator.runtimeAnimatorController;
    
  • Now you can get all its information. In your case you can probably use the default layer (layers[0]) and its stateMachine and according to your image retrieve the defaultState:

    var state = controller.layers[0].stateMachine.defaultState;
    

    or find it using Linq FirstOrdefault (put using System.Linq; at the top of the script) like e.g.

    var state = controller.layers[0].stateMachine.states.FirstOrDefault(s => s.state.name.Equals("SwimmingAnim")).state;
    
    if (state == null)
    {
        Debug.LogError("Couldn't get the state!");
        return;
    }
    
  • Finally assign the AnimationClip to this state using SetStateEffectiveMotion

    controller.SetStateEffectiveMotion(state, clip);
    

Note however that even though you can write individual animation curves for an animation clip using SetCurve unfortunately it is not possible to read them properly so it will be very difficult to do what you want

copy animations from one object, process the animation e.g. adding offset rotation, then add to another object.

You will have to go through AnimationUtility.GetCurveBindings which gets quite complex ;)

Good Luck!

Upvotes: 6

Related Questions