代码之家  ›  专栏  ›  技术社区  ›  gncc

如何在编辑器中通过脚本创建动画片段

  •  0
  • gncc  · 技术社区  · 4 年前

    我想用Unity中的编辑器创建一个AnimationClip。

    I previously got an answer 关于如何使用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
    

    如何修复此错误?

    1 回复  |  直到 4 年前
        1
  •  1
  •   KiynL    4 年前

    在获取之前交换通道并添加立方体对象:

    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
    }