Unity Replace AnimationClip At Runtime

jkjkbk·2023년 5월 2일
0

Unity

목록 보기
6/16

1. 과정

1. Animator.runtimeAnimatorController를 인자로 AnimatorOverrideController 객체를 생성
2. AnimatorOverrideController 객체에서 List<KeyValuePair<AnimationClip, AnimationClip>> 읽기
3. 가져온 List<KeyValuePair<AnimationClip, AnimationClip>>에서 원하는 AnimationClip 교체 후, AnimatorOverrideController 객체에 적용
4. 수정된 AnimatorOverrideController를 Animator.runtimeAnimatorController에 대입

2. Example

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeAnimationClipTest : MonoBehaviour
{
    public AnimationClip newClip;
    public string clipName;
    public Animator animator;

    void Start()
    {
        ShowClips(animator);
        ChangeAnimationClip(animator, clipName, newClip);
        ShowClips(animator);
    }

    public void ChangeAnimationClip(Animator targetAnimator, string targetClipName, AnimationClip toReplaceClip)
    {
    	// AnimatorOverrideController 객체 생성
        AnimatorOverrideController controller = new AnimatorOverrideController(targetAnimator.runtimeAnimatorController);
        
        // clips를 받아올 공간 할당
        List<KeyValuePair<AnimationClip, AnimationClip>> clips = new();
		// clips 가져오기
        controller.GetOverrides(clips);

        for(int i =0; i < clips.Count; i++)
        {
        	// 원하는 AnimationClip으로 교체
            if(string.Equals(clips[i].Key.name, targetClipName))
            {
                Debug.Log($"{clips[i].Key.name} -> {toReplaceClip.name}");
                clips[i] = new KeyValuePair<AnimationClip, AnimationClip>(clips[i].Key, toReplaceClip);
                break;
            }
        }
		
        // clips를 AnimatorOverrideController 객체에 적용
        controller.ApplyOverrides(clips);
        
        // AnimatorOverrideController 객체를 대입
        targetAnimator.runtimeAnimatorController = controller;
    }

    public void ShowClips(Animator toShowAnimator)
    {
        AnimationClip[] clips = toShowAnimator.runtimeAnimatorController.animationClips;
        foreach (AnimationClip clip in clips)
        {
            Debug.Log("clip : " + clip.name);
        }
    }
}
- 처음 AnimatorOverrideController 객체의 KeyValuePair<AnimationClip, AnimationClip>의 Value 값은 null이고, 수정하지 않고 targetAnimator.runtimeAnimatorController에 대입하면 그대로 똑같이 동작함

0개의 댓글