I want to create an AnimationClip using the Editor in Unity.
I previously got an answer on how to do that using MonoBehavior.
However, when I run the following code in Editor, I get an error.
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");
}
}
The following are the error messages
Assets/ExampleWindow.cs(35,31): error CS0103: The name 'GetComponent' does not exist in the current context
How can I fix this error?
CodePudding user response:
swap lanes and add cube object before get:
cubeObject = GameObject.Find("Cube");
Animation animation = cubeObject.GetComponent<Animation>();
To create animation in asset folder before play button. to review animation cntl 6 >> play:
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
}