9
13

More than 5 years have passed since last update.

[Unity] AnimationコンポーネントでAnimationを管理する

Last updated at Posted at 2017-11-24

StateMachineを使ってAnimationを管理すると確かに便利ですが、Animatorコンポーネントは処理が重たいので、ボトルネックとなって全体の処理が重くなってしまうこともあります。

簡単なように思えて、結構詰まってしまった&これといった記事がなかったのでメモを残しておきます。

Animationコンポーネントを用意する

スクリーンショット 2017-11-24 23.12.06.png

Animationの欄にAnimationClipを入れて、Play Automaticallyにチェックを入れれば、そのAnimationが再生されます。

スクリプトで動的にアニメーションを変更する

AnimationTest.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimationTest : MonoBehaviour 
{
    private Animation anim;

    public AnimationClip test_1;
    public AnimationClip test_2;

    // Use this for initialization
    void Start () 
    {
        anim = GetComponent<Animation> ();
    }

    // Update is called once per frame
    void Update () 
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            StartCoroutine ("ChangeTest_1");
        }
        if(Input.GetKeyDown(KeyCode.B))
        {
            StartCoroutine ("ChangeTest_1");
        }
    }

    /* ---------- Test_1 Coroutine ------------
     * AnimationをTest_1に変更して再生するコルーチン
     */
    IEnumerator ChangeTest_1 ()
    {
            animation.Stop ();

        yield return null;

            animation.clip = test_1;

        yield return null;

            animation.Play ("test_1");

        yield return null;
    }

    /* ---------- Test_2 Coroutine ------------
     * AnimationをTest_2に変更して再生するコルーチン
     */
    IEnumerator ChangeTest_2 ()
    {
            animation.Stop ();

        yield return null;

            animation.clip = test_2;

        yield return null;

            animation.Play ("test_2");

        yield return null;
    }
}

スクリーンショット 2017-11-24 23.25.25.png

Animationsの配列に再生したいAnimationClipを全て指定しておく必要がある。

解説

AnimationClipを動的に差し替えるだけなら、自前の変数で指定するだけで変更できる。
しかし、再生をスクリプトで制御する場合は、Animation.Play()関数に引数としてAnimationClipを渡す必要がある。
その際の参照先がAnimationsの配列なので、再生したいAnimationClipを全て入れておく必要がある。

9
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
13