Last active
October 24, 2024 05:12
-
-
Save yasirkula/86cf0b8cce094fbb93e97913eeda225b to your computer and use it in GitHub Desktop.
GC-free animation system for simple animations like scaling/moving objects or fading a UI element in Unity
This file contains 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 System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.SceneManagement; | |
namespace ScriptedAnim | |
{ | |
// Hide from Add Component menu | |
[AddComponentMenu( "" )] | |
public class ScriptedAnimations : MonoBehaviour | |
{ | |
private const bool POOL_INVALID_ANIMATIONS_ON_SCENE_CHANGE = true; | |
private static ScriptedAnimations instance; | |
private readonly List<IAnimationSystem> animationSystems = new List<IAnimationSystem>( 8 ); | |
[RuntimeInitializeOnLoadMethod( RuntimeInitializeLoadType.BeforeSceneLoad )] | |
private static void Initialize() | |
{ | |
instance = new GameObject( "ScriptedAnimations" ).AddComponent<ScriptedAnimations>(); | |
DontDestroyOnLoad( instance.gameObject ); | |
} | |
private void OnEnable() | |
{ | |
if( POOL_INVALID_ANIMATIONS_ON_SCENE_CHANGE ) | |
SceneManager.activeSceneChanged += Clear; | |
} | |
private void OnDisable() | |
{ | |
if( POOL_INVALID_ANIMATIONS_ON_SCENE_CHANGE ) | |
SceneManager.activeSceneChanged -= Clear; | |
} | |
private void Update() | |
{ | |
float deltaTime = Time.deltaTime; | |
if( deltaTime <= 0f ) | |
return; | |
for( int i = animationSystems.Count - 1; i >= 0; i-- ) | |
animationSystems[i].Execute( deltaTime ); | |
} | |
// Stop all running animations | |
public static void Clear( bool invalidAnimationsOnly = false ) | |
{ | |
for( int i = instance.animationSystems.Count - 1; i >= 0; i-- ) | |
instance.animationSystems[i].Clear( invalidAnimationsOnly ); | |
} | |
// Stop all invalid animations when active Scene changes | |
private void Clear( Scene s1, Scene s2 ) | |
{ | |
Clear( true ); | |
} | |
internal static void RegisterAnimationSystem( IAnimationSystem animationSystem ) | |
{ | |
if( animationSystem != null ) | |
instance.animationSystems.Add( animationSystem ); | |
} | |
internal static void UnregisterAnimationSystem( IAnimationSystem animationSystem ) | |
{ | |
if( animationSystem != null ) | |
instance.animationSystems.Remove( animationSystem ); | |
} | |
} | |
public interface IAnimationJob | |
{ | |
bool Execute( float deltaTime ); // Should return true while the animation is running, false when the animation is finished | |
bool CheckAnimatedObject( object animatedObject ); // Should return true if the animation is animating the "animatedObject" | |
bool IsValid(); // Should return true if the animated object is still alive | |
void Clear(); // Should clear any object references here | |
} | |
public interface IAnimationSystem | |
{ | |
void Execute( float deltaTime ); | |
void Clear( bool invalidAnimationsOnly ); | |
} | |
public class AnimationSystem<T> : IAnimationSystem where T : class, IAnimationJob, new() | |
{ | |
private const int DEFAULT_INITIAL_CAPACITY = 4; | |
private static AnimationSystem<T> instance; | |
private readonly List<T> animations; | |
private readonly List<T> animationsPool; | |
private float animationSpeed; | |
private AnimationSystem( int initialCapacity, float animationSpeed = 1f ) | |
{ | |
if( initialCapacity < 0 ) | |
initialCapacity = 0; | |
animations = new List<T>( initialCapacity ); | |
animationsPool = new List<T>( initialCapacity ); | |
this.animationSpeed = animationSpeed; | |
PopulatePool( initialCapacity ); | |
ScriptedAnimations.RegisterAnimationSystem( this ); | |
} | |
// Optional: Set the initial pool size and 'deltaTime' multiplier of the AnimationSystem | |
public static void Initialize( int initialCapacity, float animationSpeed = 1f ) | |
{ | |
if( initialCapacity < 0 ) | |
initialCapacity = 0; | |
if( instance == null ) | |
instance = new AnimationSystem<T>( initialCapacity, animationSpeed ); | |
else | |
{ | |
instance.PopulatePool( initialCapacity ); | |
instance.animationSpeed = animationSpeed; | |
} | |
} | |
// Create a new animation and return it | |
public static T NewAnimation() | |
{ | |
if( instance == null ) | |
instance = new AnimationSystem<T>( DEFAULT_INITIAL_CAPACITY ); | |
return instance.NewAnimationInternal(); | |
} | |
// Stop any animations that are animating "animatedObject" | |
public static void StopAnimation( object animatedObject ) | |
{ | |
if( instance != null ) | |
instance.StopAnimationInternal( animatedObject ); | |
} | |
// Stop all running animations | |
public static void StopAllAnimations() | |
{ | |
if( instance != null ) | |
instance.Clear( false ); | |
} | |
// Stop processing this animation system and release all of its resources | |
public static void Kill() | |
{ | |
ScriptedAnimations.UnregisterAnimationSystem( instance ); | |
instance = null; | |
} | |
public void Execute( float deltaTime ) | |
{ | |
deltaTime *= animationSpeed; | |
for( int i = animations.Count - 1; i >= 0; i-- ) | |
{ | |
if( !animations[i].Execute( deltaTime ) ) | |
RemoveAnimationAt( i ); | |
} | |
} | |
private T NewAnimationInternal() | |
{ | |
T animation; | |
if( animationsPool.Count > 0 ) | |
{ | |
int lastPooledIndex = animationsPool.Count - 1; | |
animation = animationsPool[lastPooledIndex]; | |
animationsPool.RemoveAt( lastPooledIndex ); | |
} | |
else | |
animation = new T(); | |
animations.Add( animation ); | |
return animation; | |
} | |
private void StopAnimationInternal( object animatedObject ) | |
{ | |
for( int i = animations.Count - 1; i >= 0; i-- ) | |
{ | |
if( animations[i].CheckAnimatedObject( animatedObject ) ) | |
RemoveAnimationAt( i ); | |
} | |
} | |
private void RemoveAnimationAt( int index ) | |
{ | |
animations[index].Clear(); | |
animationsPool.Add( animations[index] ); | |
// Replace the finished animation with the last animation | |
int lastAnimationIndex = animations.Count - 1; | |
animations[index] = animations[lastAnimationIndex]; | |
animations.RemoveAt( lastAnimationIndex ); | |
} | |
private void PopulatePool( int capacity ) | |
{ | |
for( int i = capacity - animationsPool.Count; i > 0; i-- ) | |
animationsPool.Add( new T() ); | |
} | |
// Pool all running animations | |
public void Clear( bool invalidAnimationsOnly ) | |
{ | |
if( invalidAnimationsOnly ) | |
{ | |
for( int i = animations.Count - 1; i >= 0; i-- ) | |
{ | |
if( !animations[i].IsValid() ) | |
RemoveAnimationAt( i ); | |
} | |
} | |
else | |
{ | |
for( int i = animations.Count - 1; i >= 0; i-- ) | |
{ | |
animations[i].Clear(); | |
animationsPool.Add( animations[i] ); | |
} | |
animations.Clear(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ScriptedAnimations is an alternative to frequently called coroutines or DOTween animations. Unlike these two systems, ScriptedAnimations will not cause any GC allocations for two reasons:
The downsides are:
Here's an example IAnimationJob:
And here's how to use it: