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

Why does it say character is a nil value?

I am having trouble on why it says Character is a nil value, this is the error: 19:19:21.294 - Players.Microsoft_Net.Backpack.Tool.LocalScript:3: attempt to index local 'Character' (a nil value)

Here is the code :

local Tool = script.Parent
local Player = game.Players.LocalPlayer
local Humanoid = Player.Character:FindFirstChild("Humanoid")
local Animation = Humanoid:LoadAnimation(Tool.Animation)

Tool.Equipped:Connect(function()
    Animation:Play()
end)

Help?

1 answer

You can't assume the character is loaded by the time you reference it in your script; in fact, it will virtually never be loaded in time if you try to reference it at the beginning of a local script. You have to wait for it:

local Tool = script.Parent
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local Animation = Humanoid:LoadAnimation(Tool.Animation)
Tool.Equipped:Connect(function()
    Animation:Play()
end)

5 comments

0

Now it says humanoid is a nil value?

0

You should wait for the humanoid as well. I thought that might happen. If something you expect to be there is nil, that means you should wait for it (in most cases like this). I'll edit the script.

0

Thank you, I learned something today definitely, but would it be, local Humanoid = Character:WaitForChild("Humanoid"):Wait() because that didn't really work. 

0

I'm fairly certain that's not what you want.

0

Definitely not. Wait() is a method that can only be used on events. WaitForChild() already has an active yield and it isn't an event.

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