AnimationLoader - Guarantee animations load correctly

There is quite a lot of bugs that can come along with loading animations such as the first time they get played, they are delayed e.t.c.

This module ensures that you get no bugs when loading animations.

local TIME_OUT = 10
function AnimationUtils.LoadAnimations(Character, Animations : {})
	local LoadedAnimationTracks = {} 
	
	local Timer = tick()
	while tick() - Timer < TIME_OUT and not Character:IsDescendantOf(workspace) do 
		task.wait(.1)
	end
	
	local Humanoid = Character:WaitForChild("Humanoid")
	local Animator : Animator = Humanoid:WaitForChild("Animator")
	
	for _, AnimationObject : Animation in pairs(Animations) do 
		if AnimationObject:IsA("Animation") then 
			LoadedAnimationTracks[AnimationObject.Name] = Animator:LoadAnimation(AnimationObject)
		end
	end
	
	for _, LoadedAnimation in pairs(LoadedAnimationTracks) do 
		LoadedAnimation:Play()
		LoadedAnimation:Stop(0)
	end
	
	return LoadedAnimationTracks
end

All you have to do is give it the players character and then a table of animations. The easiest way to do this is to have a folder with all of the animations you want to load then do:

local MyAnimations = AnimationUtils.LoadAnimations(Character, [LocationOfFolder]:GetChildren())

This will return a dictionary of the animations. It sets the keys to each AnimationTrack (a loaded animation) to the animations name inside the folder. For example lets say you have this folder:

Screenshot_1341

And then you did:

local AnimationFolder = game:GetService("ReplicatedStorage"):WaitForChild("Animations")
local MyAnimations = AnimationUtils.LoadAnimations(Character, AnimationFolder:GetChildren()

The variable “MyAnimations” here is a dictionary that has this inside of it:

print(MyAnimations)
-- Would print:
{
Running = AnimationTrack
Jump = AnimationTrack
}

Hope this helps someone.

4 Likes