我想使用 Unity 中的編輯器創建一個 AnimationClip。
我之前得到了一個關于如何使用 MonoBehavior 來做到這一點的答案。
但是,當我在編輯器中運行以下代碼時,出現錯誤。
using UnityEngine;
using UnityEditor;
using System.Collections;
using System;
using System.IO;
using System.Text;
public class ExampleWindow : EditorWindow {
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;
[MenuItem("Window/ApplyAnimation")]
public static void ShowWindow ()
{
GetWindow<ExampleWindow>("ApplyAnimation");
}
void OnGUI ()
{
GUILayout.Label("Apply animation", EditorStyles.boldLabel);
if (GUILayout.Button("Apply animation"))
{
ApplyAnimation();
}
}
void ApplyAnimation()
{
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");
}
}
以下是錯誤資訊
Assets/ExampleWindow.cs(35,31): error CS0103: The name 'GetComponent' does not exist in the current context
我該如何解決這個錯誤?
uj5u.com熱心網友回復:
在獲取之前交換通道并添加立方體物件:
cubeObject = GameObject.Find("Cube");
Animation animation = cubeObject.GetComponent<Animation>();
在播放按鈕之前在資產檔案夾中創建影片。查看影片 cntl 6 >> 播放:
void ApplyAnimation()
{
cubeObject = Selection.activeGameObject;
if (!cubeObject) return;
var _animation = cubeObject.GetComponent<Animation>();
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/qianduan/470020.html