Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Attempt to call a nil value in my loop script?

Asked by 4 years ago

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:

1local char = script.Parent:GetChildren()
2 
3for i = 1, #char do
4local hum = char:WaitForChild("Humanoid")  
5local animation = hum:LoadAnimation(game.Workspace.CultistAnimations.Cheer)
6animation:Play()
7end

Any help is appreciated

0
Are all of these NPCs in a model? Or are they free objects in the workspace? Vxpper 101 — 4y
0
They're in a model iiPizzaCraver 71 — 4y

1 answer

Log in to vote
2
Answered by 4 years ago

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.

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

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

01local humanoid
02local characters = script.Parent:GetChildren()
03 
04for i,v in pairs(characters) do
05    if v:FindFirstChild("Humanoid") then
06        humanoid = v
07        local animation = humanoid:LoadAnimation(game.Workspace.CultistAnimations.Cheer)
08        animation:Play()
09    end
10end

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

0
Thanks! I fixed the nil value that occurred after using this script and now it all works. Thank you! iiPizzaCraver 71 — 4y
Ad

Answer this question