Am I doing this the right way? Randomizing combat system animations

  1. I want to achieve randomized animation every time I click for my combat system.

  2. Since I am pretty new to scripting I stumbled against another math.random issue.

the error says "Players.Dev_Simphony.Backpack.CombatSystem:20: invalid argument #2 to ‘random’ (interval is empty) "

If you can help that would be awesome since know that this mistake should be just a stupid mistake that I made because I am new to randomizing something in tables.

local Player = game.Players.LocalPlayer
local character = Player.Character
local UIS = game:GetService("UserInputService")
local mouse = Player:GetMouse()



mouse.Button1Down:Connect(function()
	local humanoid = Player.Character.Humanoid
	local punches = {
		leftPunch = script.Parent.CombatSystem.LeftPunch.AnimationId,
		
		RightUppercut = script.Parent.CombatSystem.RightUpperut.AnimationId,
		
		LeftUpprecut = script.Parent.CombatSystem.leftUpperut.AnimationId,
		
		RightPunch = script.Parent.CombatSystem.RightPunch.AnimationId
	}
	
	local anim = humanoid:LoadAnimation(math.random(1,#punches))
	
	anim:PLay()
	
end)

Your issue is because y ou’re trying to get the length of a dictionary using the length operator, it always returns 0 for dictionaries. The length operator, # only works for strings and tables

In your case you’d have to use a custom function to get the length

Something like this

local function lengthDictionary(dictionary)
    local length = 0
    for _ in pairs(dictionary) do
       length += 1
    end
    return length
end

Edit: Wait, can’t you just use a table instead of a dictionary for your usecase?

1 Like

I see. So I need to do this??

local function lengthDictionary(dictionary)
	local length = 0
	for _ in pairs(dictionary) do
		length += 1
	end
	return length
end

local anim = humanoid:LoadAnimation(math.random(1,#lengthDictionary))

anim:Play()

nvm it gives an error I understood it wrong
"Players.Dev_Simphony.Backpack.CombatSystem:28: attempt to get length of a function value "

No actually you’re better off using a table for your case. You also had 2 other issues

You were only going to give LoadAnimation a number, it expects an animation instance. And in your punches table, you were giving animation ids, so that would error

Use this

local Player = game.Players.LocalPlayer
local character = Player.Character
local UIS = game:GetService("UserInputService")
local mouse = Player:GetMouse()

mouse.Button1Down:Connect(function()
	local humanoid = Player.Character.Humanoid
	local punches = {
		script.Parent.CombatSystem.LeftPunch,
		script.Parent.CombatSystem.RightUpperut,
		script.Parent.CombatSystem.leftUpperut,
		script.Parent.CombatSystem.RightPunch
	}
	
	local anim = humanoid:LoadAnimation(punches[math.random(#punches)])
	anim:Play()
end)
1 Like

woah awesome. Thanks for sharing!! It is working indeed and its looking awesome!!

1 Like