How to stop Value to returning to 0 over Remote Event

I am trying to send over a value from a local script to a server script but I don’t want it to keep returning to 0, heres what I mean

From the local script I want to send a value of 0

and in the server script add one to it

But everytime the remoteevent is fired from the local script it sets the counter back to 0
And I don’t want that, how would I keep the same value that the server adds on?

1 Like

The first argument in .OnServerEvent and .OnServerInvoke() is always player, which cannot be spoofed by exploiters.

event.OnServerEvent:Connect(function(player, counter)

For all additional arguments, always make sure they truly are what server expects, for example by type checking.

if type(counter) ~= "number" then return; end

Bear in mind that adding a value this way only creates a variable on server and adds to it. If you want the client to see the change, you would have to create a ValueBase or Attribute for server to modify and replicate back to the client.

Suppose you have a NumberValue in workspace called Counter.

local counter = workspace.Counter


local counter = workspace.Counter

	counter.Value += 1

Use a RemoteFunction instead of a RemoteEvent.

As you may know, functions can return values through return. You can do the same with RemoteFunctions, except they are used to create a communication between the client and the server.

-- Client
local RemFunc = game.ReplicatedStorage.RemoteFunction
local counter = 0
counter = RemFunc:InvokeServer(counter)

-- Server
local RemFunc = game.ReplicatedStorage.RemoteFunction
RemFunc.OnServerInvoke = function(player, counter)
   return counter + 1

If you execute this code, you’ll see the client will print ‘1’ as the value of ‘counter’ was set to what the server returned, aka counter + 1.

*Note that this code assumes you have a RemoteFunction called exactly “RemoteFunction” in ReplicatedStorage. If you don’t have one, create one.

1 Like

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