プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

Unity3D スクリプトによるアニメーションクリップ作成

 
 

■①CubeオブジェクトにAnimationコンポーネントを追加する

 
 


■②ソース

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sample : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //アニメーションクリップのインスタンス
        AnimationClip clip = new AnimationClip();

        //アニメーションコントローラーではなくアニメーションクリップ単体で操作する為の設定
        clip.legacy = true;

        //値の変化を設定
        //Linear⇒直線的な変化
        //引数(開始時間, 開始値, 終了時間, 終了値)
        AnimationCurve curve = AnimationCurve.Linear(0f, 0f, 3f, 0f);

        //キーフレームの設定
        //引数(時間, 値)
        //1.5秒の時点でz軸の値を5fにしている
        Keyframe key = new Keyframe(1.5f, 5f);

        //アニメーションカーブにキーフレームを追加
        curve.AddKey(key);

        //アニメーションクリップにアニメーションカーブをセット
        //引数(パスの指定, タイプ, 操作項目名, アニメーションカーブ)
        clip.SetCurve("", typeof(Transform), "localPosition.z", curve);

        //ラップモードの設定
        //ループに設定
        clip.wrapMode = WrapMode.Loop;

        //アニメーションインスタンス
        Animation animation = GetComponent<Animation>();

        //アニメーションにアニメーションクリップを組み込む
        //引数(アニメーションクリップ, 名前)
        animation.AddClip(clip, "clip");

        //アニメーションを再生
        animation.Play("clip");
    }

    // Update is called once per frame
    void Update()
    {

    }
}

 
 


■エンターでアニメーションクリップを変更するサンプルコード

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sample : MonoBehaviour
{
    Animation anim;
    bool flag = false;

    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animation>();
        AnimationClip clip1 = new AnimationClip();
        clip1.legacy = true;
        AnimationCurve curve1 = AnimationCurve.Linear(0, 0, 3, 0);
        Keyframe key1 = new Keyframe(1.5f, 3);
        curve1.AddKey(key1);
        clip1.SetCurve("", typeof(Transform), "localPosition.z", curve1);
        clip1.wrapMode = WrapMode.Loop;
        anim.AddClip(clip1, "clip1");

        AnimationClip clip2 = new AnimationClip();
        clip2.legacy = true;
        AnimationCurve curve2 = AnimationCurve.Linear(0, 0, 3, 0);
        Keyframe key2 = new Keyframe(1.5f, 3);
        curve2.AddKey(key2);
        clip2.SetCurve("", typeof(Transform), "localPosition.y", curve2);
        clip2.wrapMode = WrapMode.Loop;
        anim.AddClip(clip2, "clip2");

        anim.Play("clip1");
    }

    // Update is called once per frame
    void Update()
    {
        //エンターキー押下時
        if (Input.GetKeyDown(KeyCode.Return)) {
            if (flag) {
                //即座に切替
                anim.PlayQueued("clip2", QueueMode.PlayNow);
                flag = !flag;
            } else {
                //CrossFade()の第二引数で切替までの時間を設定
                anim.CrossFade("clip1", 1f);
                flag = !flag;
            }
        }
    }
}