Last active
February 15, 2025 18:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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