Erratic behaviour getting PlayerScripts

Hi guys,

I’m new to Roblox dev and I’m pretty sure I’m messing up, so apologies upfront.

What I’m trying to do is:
From a client script I’m trying to access PlayerScripts folders, and this is what I am doing:

local PLAYERS_SERVICE = game:getService("Players")

local playerScripts = PLAYERS_SERVICE.LocalPlayer:WaitForChild("PlayerScripts")

local KEY_BINDINGS = require(playerScripts.KeyBindings)

Essentially KeyBindins.lua is a module that contains some information shared across other client scripts, and on this particular script (above) I’m trying to require this module… the problem is that sometimes it does work as expected, and, sometimes I get: "KeyBindings is not a valid member of PlayerScripts “Players.OliePapis.PlayerScripts”

Not sure if I am on the right track, but it seems like this error has to due with some race conditions given it sometimes works just fine.

Again, I’m pretty sure I’m missing something, just don’t know what.

Thanks

2 Likes

A similar thing happens with GUI. Try adding this to the start of your code:

repeat task.wait() until game.Players.LocalPlayer.PlayerScripts:FindFirstChild("KeyBindings")

This will not run your code until it finds the KeyBindings object.

Here’s the documentation to Instance:WaitForChild()

Documentation

Thanks for you reply,

The question though is: Is it the way to go for all module dependencies a script might have?

Some parts of games, usually playergui, keybindings, etc, load in slightly later than scripts run. From my knowledge, it depends on the module dependency.