我想在腳本中針對 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?這段代碼有一個開始功能,但我不想和開始同時創建影片,我想把它用作編輯器腳本。
uj5u.com熱心網友回復:
我找到了解決方案。首先你需要知道沒有Animator
is的影片系統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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/471736.html
標籤:unity3d
上一篇:移動到圓圈區域,然后捕捉到網格?