Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Attempt to call a nil value in my loop script?

I am trying to make a script that animates a bunch of NPCs all at once. However, in the output, it says:

attempt to call a nil value

It is on line 4 and I cannot figure out what is wrong with it

This is the code:

local char = script.Parent:GetChildren()

for i = 1, #char do
local hum = char:WaitForChild("Humanoid")	
local animation = hum:LoadAnimation(game.Workspace.CultistAnimations.Cheer)
animation:Play()
end

Any help is appreciated

2 comments

0

Are all of these NPCs in a model? Or are they free objects in the workspace?

0

They're in a model

1 answer

✓ Accepted answer

I imagine that the script is parented to only one character. In that case, it is better that you directly reference the humanoid than using :GetChildren() and play the animation.

local humanoid = script.Parent:WaitForChild("Humanoid")
local animation = humanoid:LoadAnimation(game.Workspace.CultistAnimations.Cheer)
animation:Play()

Or if for some reason, the characters are all in a folder, you can do:

local humanoid
local characters = script.Parent:GetChildren()

for i,v in pairs(characters) do
	if v:FindFirstChild("Humanoid") then
		humanoid = v
		local animation = humanoid:LoadAnimation(game.Workspace.CultistAnimations.Cheer)
		animation:Play()
	end
end

The problem is that the script itself is a child of its parent and the script has no humanoid which throws a nil value.

1 comment

0

Thanks! I fixed the nil value that occurred after using this script and now it all works. Thank you!

This discussion is preserved as it was. New answers, comments, and votes are closed.