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)
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.