Blend Tree code example

Hello everyone,
I’ve trying to find some examples of working with Blend Trees by code, without luck.
Specifically, I’m trying to add some animation clips dynamically to a blend tree and then use some parameter in order to tweak the blend tree. Could you guys provide with an example and/or post some code?

Thanks in advance,

1 Like

Taken directly from our Runtime test,
It does create a controller,
add a parameter called BlendEvent
Create a blend tree and setup two clip

By default blend tree a created as Simple1D

var runClip = (AnimationClip)AssetDatabase.LoadAssetAtPath("Assets/Mecanim/run.fbx", typeof(AnimationClip));
var strafeClip = (AnimationClip)AssetDatabase.LoadAssetAtPath("Assets/Mecanim/strafe.fbx", typeof(AnimationClip));
var controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath("Assets/Mecanim/CanBlendToState.controller");
 controller.AddParameter("BlendEvent", AnimatorControllerParameterType.Float);

UnityEditor.Animations.BlendTree blendTree;
controller.CreateBlendTreeInController("BlendState", out blendTree, 0);
blendTree.name = "Blend Tree";
blendTree.blendParameter = "BlendEvent";
blendTree.AddChild(runClip);
blendTree.AddChild(strafeClip);
3 Likes

Thanks so much for your response.
And how can I add an exit transition to the blendTree from there?

Animations.AnimatorState state = controller.CreateBlendTreeInController("BlendState", out blendTree, 0);
state.AddExitTransition();
1 Like

I know is an old topic but does this works in the build too? or just in the Editor mode

it does only work in the editor, you cannot modify a controller at runtime

My Animancer plugin would let you do this dynamically at runtime as shown in this image: .

U did use unityEditor, it is not possble to use this code on runtime such as webgl or mobile publish etc.

It’s very helpful. but how to add a blend tree in a sub-state machine in code?