AnimationControllerをGUIで作りたくない時はPlayableAnimationを使おう

f:id:peroon:20181121122352p:plain

  • Aボタンを押したらパンチ
  • Bボタンを押したらキック
  • ブレンドなしに最初から再生
  • そういう単純な状況を想定しています
  • キャラに以下の PlayableAnimation.cs を付け、Animation Clipを2つ設定します

f:id:peroon:20181121121938p:plain

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Animations;

[RequireComponent(typeof(Animator))]
public class PlayableAnimation : MonoBehaviour {

    public List<AnimationClip> clipList;
    List<AnimationClipPlayable> playableList;
    PlayableGraph graph;
    Animator animator;
    AnimationPlayableOutput output;
    
    void Start () {
        animator = this.GetComponent<Animator>();
        graph = PlayableGraph.Create();
        playableList = new List<AnimationClipPlayable>();
        output = AnimationPlayableOutput.Create(graph, "output", animator);

        foreach (var animationClip in clipList){
            var clipPlayable = AnimationClipPlayable.Create(graph, animationClip);
            playableList.Add(clipPlayable);
        }

        // Test
        StartCoroutine(TestCoroutine());
    }

    public void StartAnimation(int index)
    {
        output.SetSourcePlayable(playableList[index]);
        playableList[index].SetTime(0);
        graph.Play();
    }

    IEnumerator TestCoroutine()
    {
        yield return new WaitForSeconds(0.5f);
        StartAnimation(0);
        yield return new WaitForSeconds(1.0f);
        StartAnimation(1);
    }

    void OnDestroy()
    {
        graph.Destroy();
    }
}
  • テスト(動作確認)が最初から付いているので、UnityエディタでPlayして2つのアニメーションが順に実行されれば、正しく動いています

Unityで神になる本。

Unityで神になる本。