Skip to content

Instantly share code, notes, and snippets.

@yasirkula
Last active March 8, 2024 02:28
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yasirkula/86cf0b8cce094fbb93e97913eeda225b to your computer and use it in GitHub Desktop.
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
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();
}
}
}
}
@yasirkula
Copy link
Author

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:

  1. No delegates are used, each IAnimationJob knows exactly what its task is since the task is hardcoded into the IAnimationJob
  2. IAnimationJobs are automatically pooled when finished so that they can be reused (however, creating new IAnimationJob instances when the pool is empty WILL result in unavoidable GC allocation)

The downsides are:

  1. Requires a little more code, each animation is essentially a class that extends IAnimationJob (see example code below)
  2. No built-in alternatives for WaitForSeconds like yield operations, thus ScriptedAnimations are mostly useful for simple animations that run very frequently

Here's an example IAnimationJob:

using ScriptedAnim;
using UnityEngine;

// This IAnimationJob scales an object to the specified value in 'duration' seconds
public class ScaleObjectJob : IAnimationJob
{
	private Transform transform;
	private Vector3 initialScale;
	private Vector3 targetScale;
	private float t, tMultiplier;

	public void Initialize( Transform transform, Vector3 targetScale, float duration )
	{
		this.transform = transform;
		this.targetScale = targetScale;
		initialScale = transform.localScale;

		t = 0f;
		tMultiplier = 1f / duration;
	}

	// Should return true while the animation is running, false when the animation is finished
	public bool Execute( float deltaTime )
	{
		t += deltaTime * tMultiplier;
		if( t < 1f )
		{
			transform.localScale = Vector3.LerpUnclamped( initialScale, targetScale, t );
			return true;
		}

		transform.localScale = targetScale;
		return false;
	}

	// Should return true if the animation is animating the "animatedObject",
	// or simply return false if AnimationSystem.StopAnimation(animatedObject) won't be used
	public bool CheckAnimatedObject( object animatedObject )
	{
		return ReferenceEquals( transform, animatedObject );
	}

	// Should return true if the animated object is still alive; invalid animations will
	// automatically be stopped when active Scene changes
	public bool IsValid()
	{
		return transform;
	}

	// Should clear any object references here
	public void Clear()
	{
		transform = null;
	}
}

And here's how to use it:

using UnityEngine;

class ScaleObjectJobExampleUsage
{
	// Optional: Set the initial pool size and 'deltaTime' multiplier of the ScaleObjectJob animation
	public void Initialize( int poolSize, float timeMultiplier )
	{
		AnimationSystem<ScaleObjectJob>.Initialize( poolSize, timeMultiplier );
	}

	public void ScaleObjectRandomly( Transform obj, float duration )
	{
		AnimationSystem<ScaleObjectJob>.NewAnimation().Initialize( obj, Random.insideUnitSphere, duration );
	}

	// Force stop ScaleObjectJob animations that are currently scaling 'obj'
	public void StopAnimatingObject( Transform obj )
	{
		AnimationSystem<ScaleObjectJob>.StopAnimation( obj );
	}

	// Force stop all ScaleObjectJob animations
	public void StopAllAnimations()
	{
		AnimationSystem<ScaleObjectJob>.StopAllAnimations();
	}
}

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