Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How to modify animation properties with script

Discussion in 'Animation' started by brokaplan, Dec 20, 2022.

  1. brokaplan

    brokaplan

    Joined:
    Jun 11, 2022
    Posts:
    2
    In 2D project, i want to modify my sword animation rotation to increase the max swing degrees(starting from 90 to 360 by 30 per upgrade), i am trying to test it by pressing "K" button but it is not working. Both upgrade and animator.Play function not working. A little help is appreciated :)

    This script is attached to the sword object in the scene. Animator Controller("Sword") attached to the sword object as well. And "SwordSwing" animation set in animator controller.

    SwordSwing property is Rotation.z - key[0] at 0 frame, 0 value // key[1] at 60 frame, -90 value

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class SwordAnimationController : MonoBehaviour
    7. {
    8.     Animator animator;
    9.     float curveUpgradeValue = -30f;
    10.     float curveLastValue;
    11.     AnimationCurve curve;
    12.     AnimatorClipInfo[] clips;
    13.     Keyframe[] keys;
    14.  
    15.     private void Start()
    16.     {
    17.         keys = new Keyframe[2];
    18.         keys[0] = new Keyframe(0.0f, 0.0f);
    19.         keys[1] = new Keyframe(1.0f, -90.0f);
    20.         curveLastValue = keys[1].value;
    21.         curve = new AnimationCurve(keys);
    22.         curve.preWrapMode = WrapMode.ClampForever;
    23.  
    24.         animator = GetComponent<Animator>();
    25.         clips = animator.GetCurrentAnimatorClipInfo(0);
    26.         clips[0].clip.SetCurve("", typeof(Transform), "localEulerAngles.z", curve);
    27.     }
    28.  
    29.     private void Update()
    30.     {
    31.         if (Input.GetKeyDown(KeyCode.K))
    32.         {
    33.             upgradeSwordArea(curve, clips);
    34.  
    35.             animator.Play("SwordSwing");
    36.         }
    37.     }
    38.  
    39.     public void upgradeSwordArea(AnimationCurve curve, AnimatorClipInfo[] clips)
    40.     {
    41.         curve.keys.SetValue(curveLastValue + curveUpgradeValue, 1);
    42.         curveLastValue = keys[1].value;
    43.         curve.preWrapMode = WrapMode.ClampForever;
    44.  
    45.         curve.MoveKey(1, keys[1]);
    46.  
    47.         clips[0].clip.SetCurve("", typeof(Transform), "localEulerAngles.z", curve);
    48.     }
    49. }