【Unity】Animationを再生し、終了するまで待機する拡張メソッドを作成する

はじめに

今回はAnimationでAnimationClipを再生し、終了するまで待機する拡張メソッドを紹介します

UIのアニメーション等のシンプルなアニメーションではAnimatorを使用するよりもAnimationで再生する方が処理負荷が軽く、実装もシンプルなのでそこそこ使える拡張メソッドだと思います

環境はUnity 2021.3.25f1です

コード

using System.Collections;
using UnityEngine;
/// <summary>
/// アニメーションの拡張メソッド
/// </summary>
public static class AnimationExtension 
{
    /// <summary>
    /// アニメーションを再生し、アニメーションが終了するまで待機する
    /// ループ設定は考慮してないので注意
    /// </summary>
    /// <param name="self"></param>
    /// <param name="clip"></param>
    /// <returns></returns>
    public static IEnumerator PlayAsyncAnimation(this Animation self, AnimationClip clip)
    {
        if (clip == null)
        {
            yield break;
        }
        string clipName = clip.name;

        if(self.GetClip(clipName) == null)
        {
            self.AddClip(clip, clipName);
        }

        self.Play(clipName);

        while(self.isPlaying)
        {
            yield return null;
        }
    }
}

使い方

下記のような感じで呼べばOK

これでコルーチンを使用してアニメーションの終了するまで待機できます

using System.Collections;
using UnityEngine;

public class TestScene : MonoBehaviour
{
    public Animation animation;

    public AnimationClip AvtiveClip;
  
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.S))
        {
            StartCoroutine(PlayUIAnimation());
        }
    }

    public IEnumerator PlayUIAnimation()
    {
        yield return animation.PlayAsyncAnimation(AvtiveClip);
    }
}

注意点

AnimationでAnimationClipを再生するにはLegacyでなけれはいけません

参考 https://dskjal.com/unity/set-animation-to-legacy.html