Search Unity

Change the value of a parameter of an animation clip at runtime

Discussion in 'Animation' started by amiga4K, Jan 2, 2021.

  1. amiga4K

    amiga4K

    Joined:
    Jan 30, 2018
    Posts:
    71
    Hello,

    I have the following problem: I created an animator with a FadeAudioIn animation clip that raises the audio volume from 0 to 1 using three keyframes. The keyframe at 0 sec has the volume at 0, the keyframe at 0.8 sec has the volume at 0.6 and the keyframe at 1.4 sec has the volume at 1.
    The user can change the volume of the audio so I want the values of the audio clip to change respecting the new value. I tried the following code that makes use of AnimatorOverrideController but it doesn't work:

    Code (CSharp):
    1.         if (volume == 0) return;
    2.  
    3.         Keyframe[] keys;
    4.         keys = new Keyframe[3];
    5.         keys[0] = new Keyframe(0.0f, 0.0f);
    6.         keys[1] = new Keyframe(0.8333333f, volume / 2);
    7.         keys[2] = new Keyframe(1.4333333f, volume);
    8.         var curve = new AnimationCurve(keys);
    9.  
    10.         AnimationClip animClip = new AnimationClip();
    11.         animClip.SetCurve("", typeof(AudioSource), "volume", curve);
    12.  
    13.         var animator = GameObject.Find("Audio").GetComponent<Animator>();
    14.         RuntimeAnimatorController myController = animator.runtimeAnimatorController;
    15.         var myOverrideController = new AnimatorOverrideController();
    16.         myOverrideController.runtimeAnimatorController = myController;
    17.  
    18.         myOverrideController["FadeAudioIn"] = animClip;
    19.         animator.runtimeAnimatorController = myOverrideController;
    what am i doing wrong? Is there any other way?

    P.S.
    I find it unbelievable that an engine as powerful as Unity doesn't allow you to do a simple modification of a clip parameter at runtime.