Why is loop not running after connecting with remote event

I was trying to create a thing where if player presses Gui button their name and the words “pressed button” shows on the premade text label on the middle of their screen for all players. For some reason the loop that changes the text on text label for every player doesn’t run.

Here is the local script attached to the Gui button that fires a remote event:

local button = script.Parent
local remoteEvent = game.ReplicatedStorage.RemoteEvent

button.Activated:Connect(function()
	
	remoteEvent:FireServer()
	
end)

Here is the server script located in ServerScriptStorage that is suppost to change the text label for all players:

local remoteEvent = game.ReplicatedStorage.RemoteEvent
local players = game.Players:GetChildren()

remoteEvent.OnServerEvent:Connect(function(player)
	for i, p in ipairs(players) do
		p.PlayerGui.ScreenGui.TextLabel.Text = player.Name .. " pressed button."
	end
end)

I have no idea why this doesn’t work. Does anyone have any suggestions?

1 Like

Change this to:

remoteEvent.OnServerEvent:Connect(function(player)
	for i, p in ipairs(players) do
		p.PlayerGui.ScreenGui.TextLabel.Text = p.Name .. " pressed button."
	end
end)

You cannot change guis from the server! It is very inefficent, try firing a remote event to all clients and change the text on there.

1 Like

I tried it and it doesn’t work. It seems as if anything I put in the loop won’t run.

A game I’ve been working on utilizes something similar with the only difference being that the button is not a gui button but actually a part with a click detector.

How I dealt with this was kinda simple, I just put a string value inside the button and the value changes to the player’s username after the button is pressed. I believe that remote events may be more efficient, but here is my code for now. In the meanwhile, I’ll try to find a solution to your problem instead of this workaround.

game.Workspace.button.Value.Changed:Connect(function(username)
script.Parent.Text=username.." pressed the button."
end)

local remoteEvent = game.ReplicatedStorage.RemoteEvent
local players = game.Players:GetChildren()

remoteEvent.OnServerEvent:Connect(function(player)
	remoteEvent:FireAllClients(player)
end)

Change the server script to this.

local button = script.Parent
local remoteEvent = game.ReplicatedStorage.RemoteEvent

button.Activated:Connect(function()
	
	remoteEvent:FireServer()
	
end)

remoteEvent.OnClientEvent:Connect(function(player)
script.Parent.Parent.TextLabel.Text = player.Name .. " pressed button."
end

Change the client script to this.

The issue is that you are getting the player list at runtime, when there are no players

remoteEvent.OnServerEvent:Connect(function(player)
     local players = game.Players:GetChildren()
	remoteEvent:FireAllClients(player)
end)

This should fix your issue

1 Like