Client to server event runs more than once if multiple clients

Hi,

I’m trying to do client to server communication but I’m having trouble when I fire from the client, the server runs more than once when theres more than one player. How do I only fire once from client to server regardless the amount of players are in the game?

-- server
Event.OnServerEvent:Connect(function()
    print("Fired") 
end)
-- client
Event:FireServer()

You may want to reconsider the design of whatever you’re making.

Remote events and functions are inherently designed to trigger OnServerEvent for each independent client calling :FireServer() - if fired by multiple players, your server code will naturally run more than once. What’s the use case for firing only once?

With that said, you can use variables to control this functionality, but there is almost definitely a better solution for your code.

-- server
local alreadyFired = false

Event.OnServerEvent:Connect(function(player)
    if alreadyFired then 
       return 
    end
    alreadyFired = true

    print("Fired") ---> will print once upon first :FireServer() call, all future
                   ---> calls will be blocked by the if statement
end)
3 Likes

Try

Event.OnServerEvent:Once(function()
    print("Fired") 
end)

This will automatically disconnect the event after the first time it’s been fired.

I think its because in your client script youre sinply firing the server. Therefore, whenever theres a client the server will fire. So if theres 2 players (clients) the event will fire 2 times.

A fix for this is wrapping the event in something. Like a MouseButton1Click, that way it ONLY fires when the button is clicked. You can obviously do this in many different ways to fire your event.

I hope this makes sense and if it doesnt work/u dont understand let me know

@Foxstream52
I don’t think that is what the OP is trying to do. The OP is trying to make it so that only one player (client) in a server can fire this RemoteEvent, regardless of the player count.

As @bongusbingis has suggested, you may use variables that act as a “control” to disable other clients from firing the RemoteEvent again, or, following @Fietowski’s suggestion, connect the RemoteEvent.OnServerEvent:Once() like so.

Can I send you the place file instead, I’m really bad at explaining things

To make it so the event only runs once no matter what, you can use :Once() instead of :Connect()

Event.OnServerEvent:Once(function()
   print("Fired")
end)

If this is not the issue, are you sure it’s not the other clients firing the event? To check you can do

Event.OnServerEvent:Connect(function(player)
    print(player.Name.." fired the event") 
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.