Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active April 12, 2022 08:54
Show Gist options
  • Save tsubaki/c7fb1e785287c611c31b6a66d8670923 to your computer and use it in GitHub Desktop.
Save tsubaki/c7fb1e785287c611c31b6a66d8670923 to your computer and use it in GitHub Desktop.
AnimationClipPlayableを使いまわす
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Animations;
using UnityEngine.Profiling;
public class LoopSomeAnimations : MonoBehaviour
{
[SerializeField] AnimationClip[] clips = null;
[SerializeField] float transitionTime = 0.3f;
PlayableGraph graph;
AnimationMixerPlayable mixer;
AnimationClipPlayable prePlayable, currentPlayable;
void Awake ()
{
graph = PlayableGraph.Create ();
}
void Start ()
{
// AnimationClipをMixerに登録
currentPlayable = AnimationClipPlayable.Create (graph, clips [0]);
mixer = AnimationMixerPlayable.Create (graph, 2, true);
mixer.ConnectInput (0, currentPlayable, 0);
mixer.SetInputWeight (0, 1);
// outputにmixerとanimatorを登録して、再生
var output = AnimationPlayableOutput.Create (graph, "output", GetComponent<Animator> ());
output.SetSourcePlayable (mixer);
graph.Play ();
StartCoroutine (PlayAnimations ());
}
IEnumerator PlayAnimations ()
{
for (int i = 1; i < clips.Length; i++) {
// アニメーションの時間だけ待つ
yield return new WaitForSeconds (clips[i-1].length - transitionTime);
// ClipPlayableを上書きは出来ない為、一旦mixerの1番と2番を一旦アンロード
graph.Disconnect (mixer, 0);
graph.Disconnect (mixer, 1);
// 古いアニメーションを破棄し、次に再生するアニメーションを登録する
if( prePlayable.IsValid())
prePlayable.Destroy ();
prePlayable = currentPlayable;
currentPlayable = AnimationClipPlayable.Create (graph, clips [i]);
mixer.ConnectInput (1, prePlayable, 0);
mixer.ConnectInput (0, currentPlayable, 0);
// 指定時間でアニメーションをブレンド
float waitTime = Time.timeSinceLevelLoad + transitionTime;
yield return new WaitWhile (() => {
var diff = waitTime - Time.timeSinceLevelLoad;
if (diff <= 0) {
mixer.SetInputWeight (1, 0);
mixer.SetInputWeight (0, 1);
return false;
} else {
var rate = Mathf.Clamp01 (diff / transitionTime);
mixer.SetInputWeight (1, rate);
mixer.SetInputWeight (0, 1 - rate);
return true;
}
});
}
}
void OnDestroy ()
{
graph.Destroy ();
}
}
@tsubaki
Copy link
Author

tsubaki commented Jul 29, 2017

animation 100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment