How to retrieve value through Remote Events?

I’m practicing on my coding skills and am working on Remote Events.

I’m trying to set a variable on the client by firing a Remote Event to the Server, and once the Server gets it, the Server fires the value back to the client (and the Client sets that value to the variable on their side).

So something like this:

---[[CLIENT]]---
local someEvent = ReplicatedStorage:WaitForChild("blahSomeEvent");
local someVariable = blahSomeEvent:FireServer();
---[[SERVER]]---
local someEvent = ReplicatedStorage:WaitForChild("blahSomeEvent");

function clientToServer()
    someEvent:FireClient(player, "HI")
end
someEvent.OnServerEvent:Connect(clientToServer)

It seemed to work in my mind, but not in reality.

You could try using a RemoteFunction instead of a RemoteEvent so that you can return the value.

2 Likes

Here’s how it’d be done:

local rs = game:GetService("ReplicatedStorage")
local rf = rs:WaitForChild("RemoteFunction")

local val = rf:InvokeServer()
-- Client has received the value, so lets print it since we're so giddy
print(val)
-- // SERVER \\ --
local rs = game:GetService("ReplicatedStorage")
local rf = rs:WaitForChild("RemoteFunction")

rf.OnServerInvoke = function()
	-- Send value to client
	return "hi"
end
2 Likes

I hear Remote Functions can hang the server indefinitely if the client fails to respond in time (ex: leaving as soon as the Remote Function is sent).

Would this be a problem here?

1 Like

I think this is a rumor, since personally this has never happened to me. It sort of works like WaitForChild where it yields the client’s code until the client has received the value from the server.

But no, since the server is instantly responding, it should never be a problem.

Is there a way to do it via Remote Events instead of Remote Functions like these folks are suggesting?: How do I prevent server ‘hang forever’ with RemoteFunctions - Help and Feedback / Scripting Support - Developer Forum | Roblox

Yes, it’s possible, but I’d rather use RemoteFunctions if you want it to be sleak, and know exactly when the client has received the value.
Here’s an example of using RemoteEvents to do this:

-- // CLIENT \\ --
local rs = game:GetService("ReplicatedStorage")
local remote = rs:WaitForChild("RemoteEvent")
local val

remote:FireServer()
remote.OnClientEvent:Connect(function(res)
	val = res
end)
-- // SERVER \\ --
local rs = game:GetService("ReplicatedStorage")
local remote = rs:WaitForChild("RemoteEvent")
local val

remote.OnServerEvent:Connect(function(plr)
	remote:FireClient(plr, "hi")
end)
1 Like

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