How to share variables between LocalScript and ServerScript?

How to share variables between LocalScript and ServerScript?
Only with Remote Functions/Remove Events?
Or is there an easier way?

2 Likes

You can use RemoteEvents and RemoteFunctions. As far as I know, those are the only two ways you can do it. ModuleScripts and _G/shared won’t work for server-client communication.

1 Like

In order to do this, you need a RemoteEvent.

Client Side (client to server)

-- the code below is just an example path for your remote event instance
local remoteEvent = game.your.remote.event
local myVariable = 3.4

remoteEvent:FireServer(myVariable)

Server Side (client to server)

-- the code below is just an example path for your remote event instance
local remoteEvent = game.your.remote.event
local myVariable

remoteEvent.OnServerEvent:Connect(function (receivedNumber)
   myVariable = receivedNumber
end)

Or if you want, you can reverse this:
Client Side (server to client)

-- the code below is just an example path for your remote event instance
local remoteEvent = game.your.remote.event
local myVariable

remoteEvent.OnServerEvent:Connect(function (player, receivedNumber)
   myVariable = receivedNumber
end)

Server Side (server to client)

-- the code below is just an example path for your remote event instance
local remoteEvent = game.your.remote.event
local myVariable = 3.4

game.your.remote.event:FireClient(game.Players.PlayerNumber123, myVariable)

If you want to sync your variables, you should probably fire both servers to client and client to server every time the variable is updated. This is, as far as I know, the only way to sync variables between server and client.

9 Likes