Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to make a script wait for a certain part to load into the game?

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.

  • Just a quick side note, but this is all being handled in a local script. The player variable references the LocalPlayer, and then the rest of it goes into a script loaded folder called Stats.

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?

3 comments

0

does your studio crash with that line of code?

0

No. Nothing happens at all.

0

player:WaitForChild("Stats") should wait for the stats folder. It won't execute the rest of the code until the stats exist.

2 answers

✓ Accepted answer

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

This discussion is preserved as it was. New answers, comments, and votes are closed.