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

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

Asked by 5 years ago
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?

0
does your studio crash with that line of code? T1mes 230 — 5y
0
No. Nothing happens at all. EstrangedFisherman 51 — 5y
0
player:WaitForChild("Stats") should wait for the stats folder. It won't execute the rest of the code until the stats exist. royaltoe 5144 — 5y

2 answers

Log in to vote
0
Answered by
Yuuwa0519 197
5 years ago

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.
Ad
Log in to vote
0
Answered by 5 years ago

Use WaitForChild

local inTraining = player:WaitForChild('Stats').inTraining

Answer this question