Attempt to index a nil value? Any help?

Easy fix, but it will just add for spaggheti code. If you are trying to index, for example a player’s head, you can do WaitForChild(), it will halt the script till it magically is. But if you want to make it optional, ie: you want it optional, in case there isn’t just skip it you can do if’s.

For example. I want to do:

dog = Player.Character

but dog = nil and it will error the script
Don’t use pcall, that doesn’t work usually with indexed nils.

BUT, if you do

if Player.Character then
dog = Player.Character
end

it will check, also you can add an else to it since lua 5.1 is a little bit, let’s say messy. Most of the times I had to put elses everywhere because it would just think out of the box.

Unless you want to halt the script to get an object, do :WaitForChild() like this:

let’s say you want to get the dog from workspace.

dog = workspace:WaitForChild(“Dog”)

That will halt the script till it finds Dog, if it finds it, it will continue. Both methods work, but sometimes you want it to halt and check everything, or just jump the fence if that isn’t the case.

I tried WaitForChild, did not work. Do you know why?