Possible nil value in player variable in LocalPlayer page

Hello,
while browsing on the LocalPlayer page, I noticed on the code sample in the “Loading GUIs” section that it uses Players:GetPropertyChangedSignal("LocalPlayer"):wait() to get the local player in case the LocalPlayer property returns nil. But :GetPropertyChangedSignal:wait() does not return the player variable, but nil. By the way, it uses :Wait()which is deprecated. I suppose the code below should work instead: local player = Players.LocalPlayer or Players:GetPropertyChangedSignal("LocalPlayer"):Wait() or Players.LocalPlayer

That code still wouldn’t work, since it would still return nothing. This would be the best way.
edit see jmkd3v’s reply

while not Players.LocalPlayer do
	Players:GetPropertyChangedSignal("LocalPlayer"):Wait()
end
local player = Players.LocalPlayer
1 Like

This is not the “best way” as it needlessly uses :Wait in a loop, which shouldn’t have any benefit. You wouldn’t need to add a while not. This should be sufficient:

local player = Players.LocalPlayer
if not player then
    Players:GetPropertyChangedSignal("LocalPlayer"):Wait()
    player = Players.LocalPlayer
end
1 Like

LocalPlayer is implicitly available to LocalScripts. No code should be needing to do any kind of waiting or extra work in order to get a reference to the player. None of the above methods including the method on the page itself should be used. LocalPlayer being nil should be treated as a bug now rather than an edge case and should be reported.

5 Likes

I’m fairly sure that isn’t always the case.

When creating loading GUIs using ReplicatedFirst , sometimes a LocalScript can run before the LocalPlayer is available. In this case, you should yield until it becomes available by using Instance:GetPropertyChangedSignal

Doing this isn’t for a LocalScript within StarterGui , StarterPlayerScripts or StarterCharacterScripts : these scripts can only run after a Player object is already available, and LocalPlayer will have been set by then.

I believe the dev hub is outdated on this – LocalPlayer is always non-nil in any kind of LocalScript including those running in ReplicatedFirst.

LocalPlayer can only be nil from CoreScripts which we as developers don’t have access to (unless you modify your client installation locally).

https://devforum.roblox.com/t/localplayer-timing-update/92351

5 Likes

This information isn’t up to date. LocalPlayer is never non-nil to a LocalScript regardless of its location. ReplicatedFirst scripts do not run before LocalPlayer is set (anymore).

3 Likes

Ah, I see. Looks like it’s time for an update to the LocalPlayer dev hub page.

2 Likes