AnimatorController creation in AssetPostprocessor - issue with AnimatorState.motion

Hello,

I’m trying to create a post processor that would generate automatically a dedicated animator controller for each character FBX.

I managed to get a few things working (custom object instantiation based on bones custom properties, automatic animator controller creation with 1 state per animation…), but I can’t seem to assign my animation clips to the motion of each animator state.

I have the following code:

        // Creates the controller
        AnimatorController controller = AnimatorController.CreateAnimatorControllerAtPath(assetPath.Substring(0, assetPath.LastIndexOf(".")) + "_anim.controller");
        Animator anim = g.GetComponent<Animator>();
        anim.runtimeAnimatorController = controller;
        AnimatorStateMachine rootStateMachine = controller.layers[0].stateMachine;

        // add all anim states automatically
        AnimationClip[] clips = AnimationUtility.GetAnimationClips(g);
        if (clips.Length == 0)
        {
            clips = UnityEngine.Object.FindObjectsOfType<AnimationClip>();
        }

        foreach (AnimationClip ac in clips)
        {
            // add to controller
            AnimatorState state = rootStateMachine.AddState(ac.name);
            state.motion = ac;      // this here ! doesn't seem to work
        }

When debugging the code, the motion seems to be properly applied, but once this whole routine is over the editor shows me “none” in each generated state’s motion.

Note that when debugging AnimationUtility.GetAnimationClips never finds anything therefore going into UnityEngine.Object.FindObjectsOfType every time.

What do you think ?

Thanks!

Note: on a side note, I also have an issue where all animation clips from the FBX file receive a prefix to their name (shows up like this “armature_name|clip_name” instead of just “clip_name”). Probably more related to my poor understanding of Blender though.

Ok so, after a lot of try and error I was actually pretty close to the solution when I posted this.

I checked the following post: Getting AnimationClip from FBX in the Editor (Mecanim) - Unity Engine - Unity Discussions

… and modified the method to fetch all animation clips from the imported asset to the following:

UnityEngine.Object[] objects = AssetDatabase.LoadAllAssetsAtPath(assetPath);
        foreach (UnityEngine.Object obj in objects)
        {
            AnimationClip clip = obj as AnimationClip;
            if (clip != null)
            {
                AnimatorState state = rootStateMachine.AddState(clip.name);
                state.motion = clip;
            }
        }

And that seems to work :slight_smile: