Skip to content

Instantly share code, notes, and snippets.

@celechii
Last active February 15, 2025 18:28
Show Gist options
  • Save celechii/20e0bd8209347620e376fc8a2e1e77d1 to your computer and use it in GitHub Desktop.
Save celechii/20e0bd8209347620e376fc8a2e1e77d1 to your computer and use it in GitHub Desktop.
Extremely simple animation player that allows you to play an AnimationClip with a time offset. Requires an Animator component, but doesn't need an AnimationController! Check out Unity's docs cause this is basically just that: https://docs.unity3d.com/Manual/Playables-Examples.html
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Animations;
public class AnimationPlayer : MonoBehaviour
{
public Animator Animator;
public AnimationClip CurrentClip => currentAnimation.IsValid() ? currentAnimation.GetAnimationClip() : null;
public bool IsPlaying => playableGraph.IsPlaying() && currentAnimation.GetPlayState() == PlayState.Playing;
private PlayableGraph playableGraph;
private AnimationPlayableOutput animationOutput;
private AnimationClipPlayable currentAnimation;
private void OnEnable()
{
CreatePlayableGraph();
}
private void OnDisable()
{
playableGraph.Destroy();
}
private void CreatePlayableGraph()
{
playableGraph = PlayableGraph.Create();
animationOutput = AnimationPlayableOutput.Create(playableGraph, "Animation", Animator);
}
public void Play(AnimationClip clip, float timeOffset = 0f)
{
if (!playableGraph.IsValid())
CreatePlayableGraph();
currentAnimation = AnimationClipPlayable.Create(playableGraph, clip);
animationOutput.SetSourcePlayable(currentAnimation);
currentAnimation.SetTime(timeOffset);
playableGraph.Play();
}
public void TogglePause()
{
if (currentAnimation.GetPlayState() == PlayState.Playing)
currentAnimation.Pause();
else
currentAnimation.Play();
}
public void Stop()
{
currentAnimation.Stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment