"LoadAnimation" requires an Animation object error when using a function from my modulescript a second time

Hello, I’ve looked at similar topics and they all deal with names being the same. My issue isn’t that as my animations have different names than my events and sounds.

In my gun system, I’ve decided to make my code more modular. The problem is that while trying to figure out how to store animations inside a modulescript, I realized that to play an animation you need to load it to a humanoid.

So I created a function inside the weapon’s modular script that would retrieve animations.

animations = {
		equipAnim = objectpath,
		afterEquipAnim = objectpath2,
		reloadAnimation = objectpath3,
		fireAnim = objectpath4
	},

function stats.getAnimations()
	if game:GetService("Players").LocalPlayer then
		local humanoid = game:GetService("Players").LocalPlayer.Character:FindFirstChildOfClass("Humanoid")
		if humanoid then
			local modifiedTable = stats.animations	
			for i, v in pairs(modifiedTable) do
				modifiedTable[i] = humanoid:LoadAnimation(v)
			end
			return modifiedTable
		end
	else
		return stats.animations	
	end
end

Here’s how it’s suppose to go:

If its a localscript accessing these then it will load the animations in the function. It then creates a copy of the table containing the animation objects and then, using a for loop, iterates over each one and changes the value of each key to the loaded version of those objects.

If it is a server script calling it, it will just retrieve the objects and the server script can load the animations inside itself.

The problem is that whenever you call the function twice in the client, it throws an error of “loadanimation requires an animation object” despite working the first time you called it.

Is the problem that doing:

local modifiedTable = (table containing objects)

doesn’t actually create a copy and editing the modifiedTable actually edits the original table too?

Edit: Just tested and this problem happens even when you try to call it from a different localscript.

A variable “holding” a table is merely a memory pointer. Say you do

a = {}
b = a

a and b point to the same table. If you now were to do

b.greetings = "Hello world!"
print(a.greetings)

your console would print Hello world!

You overwrite the entries in modifiedTable directly, which points to the same table as stats.animations. Second time the function is called, modifiedTable contains AnimationTracks.

To get around this, you can simply create a new table:

local modifiedTable = {}
for i, v in pairs(stats.animations) do
    modifiedTable[i] = humanoid:LoadAnimation(v)
end
return modifiedTable

Refer to “Tables as References” at the bottom of this page.

2 Likes

Thanks for the response! I was under the impression than local table = table2 just creates another table that has the same values as table2

1 Like