Is having an “animation loader” a good idea / is this code a good way to make one?
( The .Init() function runs at the start of the game, on the client )
--!strict
--// Setup
local AnimationLoader = {}
--// Services
local Players = game:GetService('Players')
local ReplicatedStorage = game:GetService('ReplicatedStorage')
--// Variables
local player = Players.LocalPlayer
local animations = ReplicatedStorage.Animations
local loadedAnimationTracks: { [string] : AnimationTrack } = {}
--// Functions
local function died()
for trackName, track in loadedAnimationTracks do
track:Destroy()
loadedAnimationTracks[trackName] = nil
end
end
local function characterAdded(character: Model)
--// Variables
--task.wait()
local humanoid: Humanoid? = character:FindFirstChildWhichIsA('Humanoid')
if (not humanoid) then return warn('Character has no humanoid.') end
local animator: Animator? = humanoid:FindFirstChildWhichIsA('Animator')
if (not animator) then return warn('Character has no animator.') end
--// Main
for _, animation: Animation in animations:GetChildren() do
loadedAnimationTracks[animation.Name] = animator:LoadAnimation(animation)
end
humanoid.Died:Once(died)
end
--// Main
function AnimationLoader.Init()
if (player.Character) then characterAdded(player.Character) end
player.CharacterAdded:Connect(characterAdded)
end
function AnimationLoader.getAnimationTrack(trackName: string): AnimationTrack
return loadedAnimationTracks[trackName]
end
--// Return
return AnimationLoader
animation loaders are always a good idea. this one is kinda underwhelming and lacks a lot of the convenience it could potentially have, but its still extremely convenient, its wrote pretty well, and its a good idea in general. animationPlayer.lua (1.6 KB)
heres a lightweight one i wrote like 8 months ago. its basically the same as yours but it covers maybe all edge cases. its also OOP and you create the animation objects via code rather than an instance.
local humanoid: Humanoid? = character:FindFirstChildWhichIsA('Humanoid')
if (not humanoid) then return warn('Character has no humanoid.') end
local animator: Animator? = humanoid:FindFirstChildWhichIsA('Animator')
if (not animator) then return warn('Character has no animator.') end
this isnt really related to your code but if you plan on using KeyframeReached then you need to make sure the animation.Length is NOT zero. otherwise youll break your keyboard. my code has a check for seeing if an animation is loaded (its length isnt zero).
in my code i have this function
which is called inside the player.CharacterAdded function. and the poll is a boolean which waits until the animation is loaded to continue on with the characterAdded function. and at the end of the characterAdded function the character is rendered as ready and the player can do XYZ, with a guarantee that all their animations will work