Argument 2 Invalid Error

Hello, I’m working on a NPC Service. Currently I have NPC appearance on hold and other things done cause I’ve been focusing on make the NPC’s playing random animations. Which is what this topic is about. I’m trying to get my NPC’s to a random animation but it keeps giving me a invalid argument 2 error.

– Error

– Code

-- Services --
local Players = game:GetService('Players')
local CollectionService = game:GetService('CollectionService')
local PhysicsService = game:GetService('PhysicsService')
-- Variables --
local NPCFolder = workspace:FindFirstChild('NPCs')
local AnimFolder = NPCFolder:FindFirstChild('Animations')
local PlrGroup = 'PlrGroup'
local NPCGroup = 'NPCGroup'
local Increments = 75
local CurrentPart = nil
----

-- Tables --
local Colors = {'Reddish brown','Burnt Sienna','Dark orange','Nougat','Light orange'}
local Tops = {'Pink','Dark stone grey','Camo','Deep blue','Pearl','Really black'} -- Will Get From Kreios
local Bottoms = {'Pink','Dark stone grey','Camo','Deep blue','Pearl','Really black'} -- Will Get From Kreios
----

-- Collision Configuration --
PhysicsService:RegisterCollisionGroup(PlrGroup)
PhysicsService:RegisterCollisionGroup(NPCGroup)
----

-- Collision Setting / For Statement --
for _,Folder in ipairs(NPCFolder.Fans:GetChildren()) do
	-- Check --
	if Folder:IsA('Folder') then
		for _,Model in ipairs(Folder:GetChildren()) do
			if Model:IsA('Model') then
				-- Check --
				for _,Asset in ipairs(Model:GetChildren()) do
					if Asset:IsA('BasePart') then
						-- Set Groups --
						Asset.CollisionGroup = NPCGroup
						Asset.Parent.PrimaryPart:SetNetworkOwner(nil)
						-- Spawn Statement --
						task.spawn(function()
							local SkinColor = Colors[math.random(1,#Colors)]
							local TopColor = Tops[math.random(1,#Tops)]
							local BottomColor = Bottoms[math.random(1,#Bottoms)]
							-- Set Colors --
							Model['Head'].BrickColor = BrickColor.new(SkinColor)
							Model['Torso'].BrickColor = BrickColor.new(TopColor)
							Model['Right Arm'].BrickColor = BrickColor.new(SkinColor)
							Model['Left Arm'].BrickColor = BrickColor.new(SkinColor)
							Model['Right Leg'].BrickColor = BrickColor.new(BottomColor)
							Model['Left Leg'].BrickColor = BrickColor.new(BottomColor)
						end)
					elseif Asset:IsA('Humanoid') then
						local Humanoid = Asset
						local Torso = Model['Torso']
						-- Disabled States --
						Humanoid:SetStateEnabled(Enum.HumanoidStateType.Climbing,false)
						Humanoid:SetStateEnabled(Enum.HumanoidStateType.Flying,false)
						Humanoid:SetStateEnabled(Enum.HumanoidStateType.StrafingNoPhysics,false)
						-- Spawn Statement --
						task.spawn(function()
							while true do
								task.wait(5)
								Humanoid:MoveTo(Torso.Position + Vector3.new(math.random(-Increments,Increments),0,math.random(-Increments,Increments)),CurrentPart)
							end
						end)
						-- Check --
						NPCFolder.Cheer.Changed:Connect(function()
							-- Table --
							local Anims = {
								Clap = AnimFolder.Cheer1,
								Jump = AnimFolder.Cheer2,
							}
							-- Check --
							if NPCFolder.Cheer.Value == true then
								task.spawn(function()
									local SelectedAnim = Humanoid:LoadAnimation(Anims[math.random(1,#Anims)])
									local Animation = SelectedAnim.Name
									Animation:Play()
								end)
							end
						end)
					end
				end
			end
		end
	end
end
----

-- On Added --
Players.PlayerAdded:Connect(function(Plr)
	Plr.CharacterAppearanceLoaded:Connect(function(Character)
		-- For Statement --
		for _,Asset in ipairs(Character:GetChildren()) do
			if Asset:IsA('BasePart') then
				Asset.CollisionGroup = PlrGroup
			end
		end
	end)
end)
----

-- Init --
PhysicsService:CollisionGroupSetCollidable(PlrGroup,NPCGroup,false)
PhysicsService:CollisionGroupSetCollidable(NPCGroup,NPCGroup,false)
----
1 Like

Try setting it up like this:

local Anims = {
[“Clap”] = AnimFolder.Cheer1,
[“Jump”] = AnimFolder.Cheer2
}
local Amount = 0

for i, v in pairs(Anims) do
Amount += 1
end

(By the way change #Anims to “Amount”)

Here you’re using “#Anims” and that wouldn’t work because of the way you set up your table. To fix that, just change it to the snippet I provided, I’m pretty sure it should work.

If you were to print (#Anims) with the way you set up your table, it would return 0. However, if you printed (#Anims) like I did, it should return the amount of animations in your table (which I assume is 2).

Now I get a error on line 80 saying “It isn’t finding a animation OBJ”

Maybe try changing:

local SelectedAnim = Humanoid:LoadAnimation(Anims[math.random(1,#Anims)])

To this maybe:

local SelectedAnim = Humanoid:LoadAnimation(AnimFolder[Anims[math.random(1,#Anims)]])

Unfortunately, picking a random value from a dictionary (as opposed to a list) is a bit more involved. As @Doomcolp pointed out, #Anims resolves to 0 because the len operator only gets the number of number indices in a table.

Small Side Note
-- This code
local Anims = {
    Clap = AnimFolder.Cheer1,
    Jump = AnimFolder.Cheer2
}
-- Is the same as this code
local Anims = {
    ["Clap"] = AnimFolder.Cheer1,
    ["Jump"] = AnimFolder.Cheer2
}

Lua always defaults to string or number keys when assigning keys in tables, and using other types as keys is explicitly done with the local tbl = {[key] = value} syntax

Assuming that you could get the “length”, since your table is indexed with strings rather than number, your code would still fail because Anims[1] and Anims[2] would resolve to nil. Instead, you need to make some code that actually picks a random value in a table, regardless of what keys it has. The following code is how I would go about choosing a random key in a given table.

local function RandomKey(tbl)
    local keys = {}
    for key, _value in pairs(tbl) do
        table.insert(keys, key)
    end
    return keys[math.random(1, #keys)]
end

Someone smarter than me can probably make it so that you don’t have to basically copy all the keys.

You can then use RandomKey in

local SelectedAnim = Humanoid:LoadAnimation(Anims[RandomKey(Anim)])

However, your code in its current state will still fail because because you should be calling SelectedAnim:Play() instead of Animation:Play().

1 Like

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