local inTraining = player.Stats.inTraining
This code is supposed to reference the player stats that get loaded in when they join the game. But it keeps erroring saying that stats doesn't exist ( or isn't a valid member of player ).
I've already figured that the script is running before the player and their stats are loaded in. But I haven't been able to find a way to prevent the script from continuing to the rest of its code until the player's stats have been loaded into their player.
I tried doing:
while player:WaitForChild("Stats") do wait() end
But that seemed to make the rest of the script to not work for some reason and I couldn't find out why.
The whole point of the script, in general, is to see if the player is in training mode, which I have a bool value that gets turned on and off when they press a key. But I have it loaded into the stats folder that is in the player. It just keeps telling me the player stats isn't there or if I put in the second code above doesn't run the rest of the script. What should I do?
AWaitForChild()
is a function that literally waits for child that doesn't exist, forever(Unless you give a maximum wait time in second parameter). Therefore, if the child already exists, the function will keep on waiting for the object since they only work when child is newly added, and won`t actually look through the children of parent object. This is why I usually combine two way to refer to the object like shown below:
local object = parent:FindFirstChild("Object") or parent:WaitForChild("Object") --checks if object exists, and if not, will wait.
Use WaitForChild
local inTraining = player:WaitForChild('Stats').inTraining