Why does this math.random animation not works

  1. What do you want to achieve? I am trying to make it so that the knife in my game randomizes the animation it uses every time so that it gives off a more authentic look.

  2. What is the issue? The animation does not work when I use said math.Random code.

This is in a server script to make sure that it doesn’t just happen for the player

local tool = script.Parent
local animR15 = script:WaitForChild("AnimationR15", 1)
local animR15_ = script:WaitForChild("AnimationR152", 1)


local canSwing = true

tool.Activated:Connect(function()
	local Character = tool.Parent
	if Character then
		local humanoid = Character:FindFirstChildWhichIsA("Humanoid")
		if humanoid then
			local LoadedAnim = nil
			local ranNumber = math.random(1,2)
			if LoadedAnim and canSwing == true then 
				if ranNumber == 1 then
					LoadedAnim:Play(animR15)
				end
				if ranNumber == 2 then
					LoadedAnim:Play(animR15_)
				end
				--humanoid.Health += 10	-- ADDS HEALTH TO YOUR CHARACTER
				canSwing = false
				wait(.7)
				canSwing = true
			end
		end
	end
end)


Im sorry if the code is complicated but I try to organize the best I can

local LoadedAnim = nil
if LoadedAnim and canSwing == true then 

You set LoadedAnim to nil so the conditional statement will never be satisfied.

local tool = script.Parent
local animR15 = script:WaitForChild("AnimationR15", 1)
local animR15_ = script:WaitForChild("AnimationR152", 1)


local canSwing = true

tool.Activated:Connect(function()
	local Character = tool.Parent
	if Character then
		local humanoid = Character:FindFirstChildWhichIsA("Humanoid")
        local animator = humanoid:FindFirstChildOfClass("Animator")
		if humanoid then
			local LoadedAnim = nil
			local ranNumber = math.random(1,2)
			if canSwing == true then 
				if ranNumber == 1 then
                    LoadedAnim = animator:LoadAnimation(animR15)
				elseif ranNumber == 2 then
					LoadedAnim = animator:LoadAnimation(animR15_)
				end

                LoadedAnim:Play()
				--humanoid.Health += 10	-- ADDS HEALTH TO YOUR CHARACTER
				canSwing = false
				wait(.7)
				canSwing = true
			end
		end
	end
end)

So at first this worked but now I run into the issue of it only playing the animation sometimes, if you have any ideas hmb

Which animation? The first one or the second one?

The code doesn’t have any issues, so it’s most likely how you created your animation. Make sure your animation’s priority is set to Action?