如何在 Unity 中通过脚本创建动画剪辑?

How to create animation clip via script in Unity?

我想在脚本中针对 Unity 中的 GameObject 创建一个 AnimationClip。但是,我不知道该怎么做。

我已将以下代码附加到 Cube 中的 GameObject 并按下播放按钮。但是,我得到了一个错误输出。

using UnityEngine;
using System.Collections;
public class LinearExample : MonoBehaviour 
{
    private float m_start_time = 0.0f;
    private float m_start_value = 0.0f;
    private float m_end_time = 5.0f;
    private float m_end_value = 10.0f;
    
    public GameObject cubeObject;
    void Start ()
    {
        Animation animation = GetComponent<Animation> ();

        cubeObject = GameObject.Find("Cube");

        if (!animation)
        {
            cubeObject.AddComponent<Animation>();
        }
        AnimationClip clip = new AnimationClip();
        AnimationCurve curve = AnimationCurve.Linear(m_start_time, m_start_value, m_end_time, m_end_value);
        clip.SetCurve("", typeof(Transform), "localPosition.x", curve);
        animation.AddClip(clip, "Move");
        animation.Play("Move");
    }
}

这是一个错误代码:

MissingComponentException: There is no 'Animation' attached to the "Cube" game object, but a script is trying to access it. You probably need to add a Animation to the game object "Cube". Or your script needs to check if the component is attached before using it. UnityEngine.Animation.AddClip (UnityEngine.AnimationClip clip, System.String newName, System.Int32 firstFrame, System.Int32 lastFrame) (at /Users/builduser/buildslave/unity/build/artifacts/MacEditor/modules/Animation/AnimationsBindings.gen.cs:400) UnityEngine.Animation.AddClip (UnityEngine.AnimationClip clip, System.String newName) (at /Users/builduser/buildslave/unity/build/artifacts/MacEditor/modules/Animation/AnimationsBindings.gen.cs:390) LinearExample.Start () (at Assets/LinearExample.cs:24)

如何修复此错误代码?

另外,如何在不玩 Unity 的情况下创建一个 AnimationClip?这段代码有一个Start函数,但是我不想在Start的同时创建Animation,我想把它作为一个Editor脚本来使用。

我找到了解决方案。没有 Animator 的动画系统是 legacy。启用它并添加剪辑如下:

void Start ()
{
    var _animation = GetComponent<Animation>();

    cubeObject = GameObject.Find("Cube");

    if (!_animation) _animation = cubeObject.AddComponent<Animation>();

    var clip = new AnimationClip();
    var curve = AnimationCurve.Linear(m_start_time, m_start_value, m_end_time, m_end_value);
    clip.SetCurve("", typeof(Transform), "localPosition.x", curve);

    clip.name = "Move"; // set name
    clip.legacy = true; // change to legacy
    
    _animation.clip = clip; // set default clip
    _animation.AddClip(clip, clip.name); // add clip to animation component

    AssetDatabase.CreateAsset(clip, "Assets/"+clip.name+".anim"); // to create asset
    _animation.Play(); // then play
}