Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Bug Swapping Animation Clip in RuntimeAnimatorController at runtime via script does not work

Discussion in 'Animation' started by Sangemdoko, Oct 5, 2023.

  1. Sangemdoko

    Sangemdoko

    Joined:
    Dec 15, 2013
    Posts:
    220
    Hi,
    I'm trying to change an Animation Clip at runtime directly in code.
    The "animationClipCopy" is created at runtime and I set its curves manually.

    The issue is that setting the runtime animation controller animation clips at runtime does not work.
    We can see this by logging the instance ID

    Code (CSharp):
    1.  
    2. Debug.Log(animationClipCopy.GetInstanceID());
    3. Debug.Log( m_RuntimeAnimatorController.animationClips[0].GetInstanceID());
    4.  
    5. m_RuntimeAnimatorController.animationClips[0] = animationClipCopy;
    6.            
    7. Debug.Log("After");
    8. Debug.Log(animationClipCopy.GetInstanceID());
    9. Debug.Log( m_RuntimeAnimatorController.animationClips[0].GetInstanceID());
    This code results in:
    Code (CSharp):
    1. -57100
    2. 3980
    3. After
    4. -57100
    5. 3980
    I was expecting
    Code (CSharp):
    1. -57100
    2. 3980
    3. After
    4. -57100
    5. -57100
    I can't set m_RuntimeAnimatorController.animationClips array because it is get only and I can't edit it for some unexplained reason


    I want to edit the animation curves at runtime so this is causing me some issues.

    So far my code works, but I'm changing the original animationClip instead of the copy. And this is a problem because it saves those changes on the animationClip asset file within the project even after exiting playmode.


    My workaround was to add a AnimationOverrideController with dummy animation clip assets in the editor, that don't matter if changed. But that's really not ideal since I use the AnimationClip name to fetch the animation clip I want to change.

    Any Advice is welcomed
     
  2. Sangemdoko

    Sangemdoko

    Joined:
    Dec 15, 2013
    Posts:
    220
    So after further testing I realised two things.

    1
    Setting animationClip curves in a build gives an error even though it works in the editor:
    Code (CSharp):
    1. Can't use AnimationClip::SetCurve at Runtime on non Legacy AnimationClips
    2
    Setting the runtimeAnimatorController animationClips directly does not work.
    BUT
    You can use an AnimatorOverrideController. And use the ApplyOverrides function to swap animation clips at runtime through code.
    They have two examples in the unity documentation:
    https://docs.unity3d.com/ScriptReference/AnimatorOverrideController.html

    I hope that helps out some of you who might be looking into this too