LoginSignup
8
6

More than 5 years have passed since last update.

UnityのAnimatorでコールバックを差し込む方法

Last updated at Posted at 2016-03-20
AnimatorFinishEventTrigger.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Animator finish event trigger.
/// </summary>
public class AnimatorFinishEventTrigger : MonoBehaviour
{
    /// <summary>
    /// Occurs when on finish animation.
    /// </summary>
    public event Action<string> OnFinishAnimation;

    /// <summary>
    /// Awake this instance.
    /// </summary>
    void Awake()
    {
        // Get a reference to the Animator Controller:
        RuntimeAnimatorController ac = GetComponent<Animator>().runtimeAnimatorController;
        string methodName = (OnFinishAnimationTrigger as Action<string>).Method.Name;

        foreach(var clip in ac.animationClips)
        {
            var finishEvent = new AnimationEvent();
            finishEvent.functionName = methodName;
            finishEvent.stringParameter = clip.name;
            finishEvent.time = clip.length;
            clip.AddEvent(finishEvent);
        }
    }

    /// <summary>
    /// Raises the finish animation trigger event.
    /// </summary>
    /// <param name="name">Name.</param>
    private void OnFinishAnimationTrigger(string name)
    {
        if(this.OnFinishAnimation != null)
        {
            this.OnFinishAnimation(name);
        }
    }
}

このAnimatorFinishEventTriggerコンポーネントを任意のゲームオブジェクトへ貼る。
これをGetComponent等で取得して、

GetComponent<AnimatorFinishEventTrigger>().OnFinishAnimation = (str)=>{Debug.Log(str)};

のようにする。

8
6
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
8
6