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

Why does it say character is a nil value?

Asked by 5 years ago

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

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

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)
0
Now it says humanoid is a nil value? Microsoft_Net 21 — 5y
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. BlueGrovyle 278 — 5y
0
Thank you, I learned something today definitely, but would it be, local Humanoid = Character:WaitForChild("Humanoid"):Wait() because that didn't really work.  Microsoft_Net 21 — 5y
0
I'm fairly certain that's not what you want. BlueGrovyle 278 — 5y
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. DeceptiveCaster 3761 — 5y
Ad

Answer this question