Should I Reuse Animation Instances or Not?

I have this Lua code for a combat system:

local comboCount = 0

function CombatSystem:GetAnimationForHit(hitNumber)
    local animations = {
        [1] = "rbxassetid://133302675095894",
        [2] = "rbxassetid://86675730184536",
        [3] = "rbxassetid://1234561",
        [4] = "rbxassetid://1234561",
        [5] = "rbxassetid://1234561"
    }
    
    return animations[hitNumber] or animations[1]
end

function CombatSystem:PerformAttack(player)
    comboData.count += 1

    -- ===== Play Animation =====
    local animationId = self:GetAnimationForHit(comboData.count)
    local animation = ReplicatedStorage.CombatSystem.AttackAnimation

    animation.AnimationId = animationId
    animator:LoadAnimation(animation):Play()
end

My question is:

Is it bad practice to use a single animation instance and just change its AnimationId depending on the player’s combo? Or is it better to create multiple animation instances and set them up when the player joins?

2 Likes

If youre loading a bunch of tracks at the same time, it might save some memory and time to reuse the same instance

but creating an animation instance parents it to nil by default, so I think the garbage collector will get rid of it after all references to it go out of scope, and memory use will be the same

so in this case the difference is probably unnoticeable and there is a very small speedup because you dont create a new instance

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.