Hello, I got an error while I was trying to make a script that animates the character when equipping. I looked through the code and couldn’t determine the problem.
Here is the code -
The error appears on line 5, and when I try to use ‘WaitForChild()’, the same thing happens except it says 'Attempt to index nil with ‘WaitForChild()’.
Here is the error, if you want to see it -
The error is likely occurring because the script cannot find the child objects “Equip” and “Hold” under the script object. Here’s the corrected code with some additional error handling:
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local equipAnim = script:FindFirstChild("Equip")
local holdAnim = script:FindFirstChild("Hold")
local humanoid = character:WaitForChild("Humanoid")
local hold = humanoid:LoadAnimation(holdAnim)
local equip = humanoid:LoadAnimation(equipAnim)
local tool = script.Parent
if not equipAnim or not holdAnim then
error("Equip or Hold animation not found")
end
tool.Equipped:Connect(function()
equip:Play()
equip.AnimationEnded:Connect(function()
hold:Play()
end)
end)
tool.Unequipped:Connect(function()
equip:Stop()
hold:Stop()
end)
This code first checks if the “Equip” and “Hold” child objects exist using FindFirstChild() to avoid the “Attempt to index nil” error. It also waits for the character to be added if it hasn’t been created yet.
Additionally, AnimationEnded event is used instead of Ended to ensure that the “Hold” animation starts playing only after the “Equip” animation has finished playing completely.