アニメーションを簡単再生するやつ
UnityのAnimationClipをアタッチしたらそれで動くやつ。
みんな求めた、みんなやってるから俺もやってみる。
ソースは下の方。
使い方
アニメーションさせたいものにアタッチする。
AnimationClipに再生したいアニメーションをいれる。
インスペクター上で扱うとこ
- animationClip
- 再生したいanimationをD&Dする。
- animatePhysics
- playAutomatically
- OnEnable()で勝手に再生されるタイプか否か
ソースコード上で扱うとこ
- OnPlay OnDone
- アニメーション開始時、終了時の処理を登録する。
- AnimationClip
- アニメーションClipを入れる
- IsPlaying
- 再生中であるかフラグ
- Play()
- 再生する
- Stop()
- 止める
using System; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Animations; [RequireComponent(typeof(Animator))] public class SimpleAnimation : MonoBehaviour { public Action OnPlay; public Action OnDone; public AnimationClip AnimationClip { set { animationClip = value; SetOutput(); } } public bool IsPlaying { get { return graph.IsPlaying(); } } public void Play() { if(!graph.IsPlaying()) { graph.Play(); } OnPlay?.Invoke(); isDone = false; if(!animationClip.isLooping) { clipPlayable.SetTime(0); } } public void Stop() { if(!graph.IsPlaying()) { return; } isDone = true; clipPlayable.SetDone(isDone); graph.Stop(); OnDone?.Invoke(); } [SerializeField] AnimationClip animationClip; [SerializeField] bool animatePhysics; [SerializeField] bool playAutomatically; Animator animator; PlayableGraph graph; AnimationClipPlayable clipPlayable; bool isInitialized; bool isDone; void OnEnable() { Initialize(); if(playAutomatically) { Play(); } } void Initialize() { if(isInitialized) { return; } animator = GetComponent<Animator>(); if(animator.runtimeAnimatorController != null) { Debug.LogWarning("AnimatorController already exists. Delete AnimatorController on Animator component."); animator.runtimeAnimatorController = null; } animator.updateMode = animatePhysics ? AnimatorUpdateMode.AnimatePhysics : AnimatorUpdateMode.Normal; graph = PlayableGraph.Create(); graph.SetTimeUpdateMode(DirectorUpdateMode.GameTime); SetOutput(); isInitialized = true; } void Update() { if(isDone) { return; } if(animationClip.isLooping) { return; } isDone = clipPlayable.GetTime() >= animationClip.length; clipPlayable.SetDone(isDone); if(isDone) { graph.Stop(); OnDone?.Invoke(); } } void SetOutput() { clipPlayable = AnimationClipPlayable.Create(graph, animationClip); var output = AnimationPlayableOutput.Create(graph, "output", animator); output.SetSourcePlayable(clipPlayable); } void OnDestroy() { graph.Destroy(); } }
終わり