Does this code seem wrong?

I’m making an Animator mechanism for my AI, which automatically plays an animation when the State of an AI changes.
The problem is that the mechanism doesn’t work. I believe that no semantic errors are occurring in my code.

-- Server-Side
-- ...
local Animator = Humanoid:WaitForChild("Animator")
local AnimationFolder = script:WaitForChild("Animations")
local Optimized = {}

for i, v in ipairs(AnimationFolder:GetChildren()) do
	if (v:IsA("Animation")) then
		Optimized[v.Name] = Animator:LoadAnimation(v)
	end
end
-- ...

The module works fine (from debugging), but the animations don’t play.
(The reason why the category is Scripting Support is that the code doesn’t work)
Thank you so much!

You aren’t even playing the animation
Optimized[v.Name] = Animator:LoadAnimation(v) Optimized[v.Name]:Play()

It’s because I truncated the part of the code that deals with playing the animation from the code that I provided.

local AnimationFunctions = {};
AnimationFunctions.ClearAnimations = function(exception)
	for i, v in ipairs(Animator:GetPlayingAnimationTracks()) do
		if (v == exception) then
			continue
		end
		v:Stop()
	end
end
AnimationFunctions.PlayAnimation = function(animation: AnimationTrack)
	if (animation.IsPlaying) then
		return
	end
	animation:Play()
end
-- Part of Module
AI.OnStateChange:Connect(function(newState)
	local value = newState.value
	for i, v in pairs(State) do
		if (value ~= v) then
			continue
		end
		local indexvalue = Optimized[i]
		if (not indexvalue) then
			return
		end
		AnimationFunctions.PlayAnimation(indexvalue)
		AnimationFunctions.ClearAnimations(indexvalue)
		return
	end
end)

Edit: removed type annotations.
Edit 2: removed semi-colons.

Here you are creating a key index in the table “Optimized”

Here you attempt to index it with a number

Wait, I forgot to mention that State is a key-value pair (string: number).
Hence the use of pairs instead of ipairs.
i: string, v: number

local State = {
    Unknown = -1,
    Idle = 0,
    Patrolling = 1,
    -- ...
}

I think this is the problem, you are playing and clearing it instantly, you probably need to wait for it to finish playing

That’s the reason why the continue statement exists in the ClearAnimations function.

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