Search Unity

Question Trying to manipulate animation clips's Keyframes using scripts.

Discussion in 'Animation' started by yigh, Jul 6, 2020.

  1. yigh

    yigh

    Joined:
    Jun 26, 2019
    Posts:
    2
    Hi everyone,
    I have some simple animations for a 2D project. My intention with my animation clip is to take my current GameObject and translate it up / sideways / etc. The tricky part where I couldn't find a solution : how to make this translation happen relative to the GameObject's current position?

    For example, if I have an object with anchoredPosition.y=20, I want to move it to 30 = (anchoredPosition.y + 10).

    Here's some code I wrote after digging around. It produces the desired effect for editing the animation clip, based on manual testing by changing Animator parameters in the Animator editor/inspector.

    However, after these script edits, the Animator component seems to be ignoring my calls to SetBool. Previously, I used the SetBool call to change states, which will then play the clip that I am editing in my script.

    After adding the below code, SetBool and GetBool on my animator returns True in logs, but my Animator inspector page still shows False.
    Code (CSharp):
    1.  
    2. Animator anim = GetComponent<Animator>();
    3. // Iterate over clips, looking for the clips I want to edit by name string.
    4. foreach (AnimationClip clip in anim.runtimeAnimatorController.animationClips)
    5. {
    6.   Keyframe[] keys = new Keyframe[2];
    7.   AnimationCurve curve;
    8.   if (clip.name == nameOfClipToModify)
    9.     {
    10.        // Set up a new curve for AnchorPos.y with my desired relative values.
    11.        keys[0] = new Keyframe(0.0f, relativeStart);
    12.        keys[1] = new Keyframe(0.6f, relativeEnd);
    13.        curve = new AnimationCurve(keys);
    14.        // clip.legacy = true;  Setting this did not matter
    15.        clip.SetCurve("", typeof(RectTransform), "m_AnchoredPosition.y", curve);
    16.     }
    17. }
    18.  
    If I omit this code, SetBool works and triggers the animation clip (although with absolute parameters for anchor position).

    Let me know what I can do (or if there's an easier way to make animations move relative to an existing position). Thanks