Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  4. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Blend Tree code example

Discussion in 'Animation' started by blumersolutions, Sep 19, 2016.

  1. blumersolutions

    blumersolutions

    Joined:
    Feb 9, 2013
    Posts:
    30
    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,
     
    nonopblic likes this.
  2. Mecanim-Dev

    Mecanim-Dev

    Unity Technologies

    Joined:
    Nov 26, 2012
    Posts:
    1,605
    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

    Code (CSharp):
    1.  
    2. var runClip = (AnimationClip)AssetDatabase.LoadAssetAtPath("Assets/Mecanim/run.fbx", typeof(AnimationClip));
    3. var strafeClip = (AnimationClip)AssetDatabase.LoadAssetAtPath("Assets/Mecanim/strafe.fbx", typeof(AnimationClip));
    4. var controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath("Assets/Mecanim/CanBlendToState.controller");
    5.  controller.AddParameter("BlendEvent", AnimatorControllerParameterType.Float);
    6.  
    7. UnityEditor.Animations.BlendTree blendTree;
    8. controller.CreateBlendTreeInController("BlendState", out blendTree, 0);
    9. blendTree.name = "Blend Tree";
    10. blendTree.blendParameter = "BlendEvent";
    11. blendTree.AddChild(runClip);
    12. blendTree.AddChild(strafeClip);
    13.  
     
  3. blumersolutions

    blumersolutions

    Joined:
    Feb 9, 2013
    Posts:
    30
    Thanks so much for your response.
    And how can I add an exit transition to the blendTree from there?
     
  4. Mecanim-Dev

    Mecanim-Dev

    Unity Technologies

    Joined:
    Nov 26, 2012
    Posts:
    1,605
    blumersolutions likes this.
  5. Noixelfer

    Noixelfer

    Joined:
    Aug 2, 2018
    Posts:
    1
    I know is an old topic but does this works in the build too? or just in the Editor mode
     
  6. Mecanim-Dev

    Mecanim-Dev

    Unity Technologies

    Joined:
    Nov 26, 2012
    Posts:
    1,605
    it does only work in the editor, you cannot modify a controller at runtime