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

Why is char nil?

Asked by 8 years ago
local player = script.Parent.Parent.Parent.Parent.Parent.Parent
local char = player.Character --This.

script.Parent.MouseButton1Click:connect(function()
    local Get = char:GetChildren() --This.
    for i = 1, #Get do
        if Get[i].ClassName == "Model" then
            local Gget = Get[i]:GetChildren()
            for i = 1, #Gget do
                if Gget[i].Name == script.Parent.Parent.Parent.Parent.TargetFolder.Target.Value then
                Gget[i].BrickColor = BrickColor.new(script.Parent.Name)
                end
            end
        end
    end
end)

0
Is this a script or Localscript? rexbit 707 — 8y
0
LocalScript. Vingam_Securis 213 — 8y

1 answer

Log in to vote
3
Answered by 8 years ago

More often than not, local scripts will load in the player before his / her character does. Because of this, it's a common procedure to give the script a chance to wait for the character, before running the next line of code.

Sometimes people will use loops such as repeat or while to wait until the character doesn't equal nil, but there's actually an easier and shorter way to do this.

Solution

There's an event called CharacterAdded for each player, and with that event, inherits a wait method. This wait isn't exactly like the one built into the global environment, it works a bit differently. Here's an example:

local Player = game.Players.LocalPlayer -- I suggest using the LocalPlayer option instead of finding the script's ancestor

local Character = Player.CharacterAdded:wait() -- Using the "wait" method will cause the script to yield until the character has been added. Once it's been added, it returns the character, which is then stored in our "Character" variable.

Possible problem?

Now, sometimes the character actually does load on time for the script to reference it right away (it's not common, but it can happen). So in this case, using the solution above would be bad, since it would wait for the character to be added, after it's already been added. So we can fix this by simply using an or statement, like this:

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:wait()

print(Character.Name) -- Will print the character's name if the character does indeed exist

So, hope that helped. If you have any questions, just let me know.

0
I always forget about that kind of stuff, I had a dumb moment. Thanks so much for the help! I'll be hoping to find you for any possibly future issues I find with other scripts! Vingam_Securis 213 — 8y
Ad

Answer this question