I need a way to generate new AnimationClip at run-time. But I found that when generate new animation clip, the “Stop Time” parameter in animation setting would be set at default of 1. Is there a way to set this at run-time not via editor.
As pointed out by @RobAtApex, the Animation component is now depreciated and should not be used for new projects.
However, the information given by @yashpal are still valid. The “only” things that change are the use of the Animator component instead of the Animation one.
First of all, you have to create an Animator controller asset in your project. In this controller, add an empty state that will be played automatically (name it as you want : Default for instance)
Then, in code, you will create (at runtime), an animator controller override and you will specify the animation clip you have created.
using UnityEngine;
public class AnimatorBehaviourScript : MonoBehaviour
{
// Drag & drop the animator component
[SerializeField]
private Animator animator;
// Specify the name of the default state of the animator
[SerializeField]
private string stateName = "Default";
private AnimatorOverrideController animOverrideController;
private AnimationClip animationClip;
void Start ()
{
AnimationClip animationClip = CreateAnimationClip();
SetClip( animationClip, stateName );
}
private AnimationClip CreateAnimationClip()
{
// Create animation clip
// This is an example
AnimationCurve translateX = AnimationCurve.Linear(0.0f, 0.0f, 2.0f, 2.0f);
AnimationClip animationClip = new AnimationClip();
animationClip.SetCurve("", typeof(Transform), "m_localPosition.x", translateX);
}
private void SetClip( AnimationClip animationClip, string state )
{
AnimatorOverrideController animatorOverrideController = new AnimatorOverrideController();
animatorOverrideController.runtimeAnimatorController = animator.runtimeAnimatorController;
animatorOverrideController[state] = animationClip;
animator.runtimeAnimatorController = animatorOverrideController;
}
}
Note, with this method you can’t generate animation based on frames or seconds into a clip. Instead you can rely on the percentage you are into a clips duration.