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 3 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:

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

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

1 answer

Log in to vote
2
Answered by 3 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.

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.

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

Answer this question