개요
- Unity Animation 상태 콜백 방법은 아래 3가지가 있다.
- key frame에 eventy를 삽입하고, 특정 method로 콜백 받는 방법
- StateMachineBehavior를 사용하는 방법
- AnimationEvent를 사용하는 방법
- 레이어가 복잡하지 않고, 애니메이션 시작과 종료 여부만 알고 싶은 경우 사용하기 괜찮다.
방법
- key frame에 eventy를 삽입하고, 특정 method로 콜백 받는 방법을, animator에 일괄적으로 적용할 수 있어서
- 시작과 종료 등의 이벤트만 처리하기 좋다고 생각한다.
[System.Serializable]
public class UnityAnimationEvent : UnityEvent<string>{};
[RequireComponent(typeof(Animator))]
public class AnimationEventDispatcher : MonoBehaviour
{
public UnityAnimationEvent OnAnimationStart;
public UnityAnimationEvent OnAnimationComplete;
Animator animator;
void Awake()
{
animator = GetComponent<Animator>();
for(int i=0; i<animator.runtimeAnimatorController.animationClips.Length; i++)
{
AnimationClip clip = animator.runtimeAnimatorController.animationClips[i];
AnimationEvent animationStartEvent = new AnimationEvent();
animationStartEvent.time = 0;
animationStartEvent.functionName = "AnimationStartHandler";
animationStartEvent.stringParameter = clip.name;
AnimationEvent animationEndEvent = new AnimationEvent();
animationEndEvent.time = clip.length;
animationEndEvent.functionName = "AnimationCompleteHandler";
animationEndEvent.stringParameter = clip.name;
clip.AddEvent(animationStartEvent);
clip.AddEvent(animationEndEvent);
}
}
public void AnimationStartHandler(string name)
{
Debug.Log($"{name} animation start.");
OnAnimationStart?.Invoke(name);
}
public void AnimationCompleteHandler(string name)
{
Debug.Log($"{name} animation complete.");
OnAnimationComplete?.Invoke(name);
}
}
출처