【Unity】Animationの最終フレームで処理を実行する

Unity勉強中の crist18 です。

アニメーションの最終フレームでCallbackを呼び出す処理を頻繁に使うので、 最終フレームでGameObjectを非表示にするコンポーネントを作ってみました。

使い方

  1. アニメーションのGameObjectにAnimationEndCallbackをアタッチする
  2. インスペクタよりCallback Typeを指定する

f:id:crist18:20150301223426p:plain

sampleでは最終フレームに達したとき、GameObjectのSetActiveをfalseにする処理を書いています。

仕組み

  • animation.clip.length でアニメーションの秒数を取得する
  • animationInfo.clip.AddEvent でキーフレームにイベントを登録する
  • イベントが登録されたフレームが再生されたときEndAnimationCallbackを呼び出す

AnimationEndCallback.cs

using UnityEngine;
using System.Collections;

public class AnimationEndCallback: MonoBehaviour
{
    [SerializeField] 
    private CallbackTypes callbackType = CallbackTypes.None;
    private bool isRegistered = false;

    public enum CallbackTypes
    {
        None,
        SetActiveFalse,
    }

    private Animator animator;
    public Animator Animator
    {
        get
        {
            if (animator == null)
            {
                animator = this.GetComponent<Animator>();
            }
            return animator;
        }
    }

    public bool HasAnimator
    {
        get { return Animator != null; }
    }
    
    void Update()
    {
        if (!this.isRegistered)
        {
            Register();
        }
    }
        
    public void Register()
    {
        if (!this.HasAnimator)
        {
            return;
        }
        if (!this.gameObject.activeInHierarchy)
        {
            return;
        }

        var currentAnimationState = this.Animator.GetCurrentAnimationClipState(0);
        foreach (var animationInfo in currentAnimationState)
        {
            var animEvent = new AnimationEvent();
            animEvent.functionName = "EndAnimationCallback";
            animEvent.time = animationInfo.clip.length;
            animEvent.intParameter = 0;
            animationInfo.clip.AddEvent(animEvent);
        }

        this.isRegistered = true;
    }

    public void EndAnimationCallback()
    {
        switch (this.callbackType)
        {
            case CallbackTypes.None:
                break;
            case CallbackTypes.SetActiveFalse:
                this.gameObject.SetActive(false);
                break;
            default:
                break;
        }
    }
}

Thanks your logs!

この記事を作成するにあたり下記のサイトを参考にさせていただきました。有難うございます!

Unity3D - アニメーションを強制的に最後のフレームにする - Qiita http://qiita.com/udzura/items/bf43048c680b3aaad44a

OnionGinger: Unity アニメーションイベント http://onionginger.blogspot.jp/2012/04/unity_21.html