LocalScript running before ModuleScript is added to client PlayerScripts?

I have a local script called ControlsScript and a module script called InputMode both inside of StarterPlayerScripts.
image

Inside of ControlsScript, at the start of the script it does:

local PlayerScripts = Players.LocalPlayer.PlayerScripts
local InputMode = require(PlayerScripts.Controls.InputMode)

When I run the game, the second line spits out the error saying Controls is not a valid member of Players.LocalPlayer.PlayerScripts
image

I tried printing the children of PlayerScripts before requiring the module and it appears only a few of the scripts have been added to PlayerScripts by the time this script runs, whereas adding a wait() beforehand would show all the scripts loaded and the module would be found and loaded perfectly fine.

print(PlayerScripts:GetChildren())
wait()
print("waited")
print(PlayerScripts:GetChildren())
local InputMode = require(PlayerScripts.Controls.InputMode)
local Enumerate = require(RepStore.Services.Enumerate)

image

This solution isn’t sufficient for me since this script creates a CharacterAdded event, and adding a wait() causes it to run after the Character is autoloaded. Is there any way to ensure all the script instances are added before they run?

It is usually recommended to use “WaitForChild” when accessing assets on the client.

Changing the dots with ":WaitForChild()"s should fix your problem.

2 Likes

Well the other problem I’m having with adding any kind of wait is that the rest of the script then runs after the player’s character autoloads, which means the CharacterAdded event it creates misses that initial character spawn. Would I have to make my own system for spawning Characters after this stuff loads then?

You shouldn’t rely on character added for the player’s first spawn on join. It is only reliable on later spawns.

Run the function in the script before or after connecting to CharacterAdded.

1 Like

Ohhh so something like this?

if Players.LocalPlayer.Character then
	BindToCharacter(Players.LocalPlayer.Character)
end
Players.LocalPlayer.CharacterAdded:Connect(BindToCharacter)

Seems to be working, thanks a ton. Was losing my mind over this lol.

1 Like

Yep that should be good.
No problem, subtle bugs like this are the worst :grinning:.

1 Like