Attempt to index nil with 'PlayerGui'

May I have an explanation of why this doesn’t function as intended? I do acknowledge that it’s a simple fix, but unfortunately I can’t find a solution. Here is the script:

game.ReplicatedStorage.HostUser.OnServerEvent:Connect(function(plr, txt)
	local function setUser()
		local plrs = game:GetService("Players")
		local plr = plrs.LocalPlayer
		local label = plr.PlayerGui.Host.SecondaryHost.Host.HostUser
		label.text = txt
	end 
	setUser()
7 Likes

You’re attempting to index LocalPlayer in a Server Script. You can’t do this. It doesn’t make sense.

Instead of defining plrto be plrs.LocalPlayeryou can just use the variable passed to the scope of your function connected to your OnServerEvent signal

However in your case it looks like you want to set the text label for some sort of UI on everyone’s client. So you will want to iterate over all the players ingame.

game.ReplicatedStorage.HostUser.OnServerEvent:Connect(function(plr, txt)
    for i, player in pairs(game.Players:GetPlayers()) do
        player.PlayerGui.Host.SecondaryHost.Host.HostUser.Text = txt
    end
end)

This code is for demonstration. You will want to build off of this code and probably not use this code directly. While I recall the server replicating GUI changes made on it to the client, I personally suggests that you do all UI changes on the client, and use a RemoteEvent to do so

24 Likes