I know about RemoteEvents, but what are RemoteFunctions for? I still dont know what for.
A RemoteFunction
allows for client <-> server communication kinda like RemoteEvents
. The difference is that you do not fire any events, you assign OnServerInvoke
to a function, think of this like a property.
The function can return values, and the calling side will yield (or pause) until a result is received.
There cannot be multiple OnServerInvoke
s either.
```lua local rf = Instance.new("RemoteFunction"); rf.Name = "testRF"; rf.Parent = game:GetService("ReplicatedStorage"); local items = game:GetService("ServerStorage").items; --// some folder with weapons
function rf.OnServerInvoke(client, weaponName) --// client is the player that invoked return items[weaponName].price.Value; --// tools have a numberValue named price whose value is the price of the weapon end; ```
```lua local result = game:GetService("ReplicatedStorage"):WaitForChild("testRF"):InvokeServer("AK-47"); print(result); -- output;
--[[ 450 ]]-- -- random price idk
```
On the client, you OnClientInvoke
, though it is not recommended and you actually rarely need to use this, it is not recommended because it is possible for an exploiter to return bad information or not return at all, the latter being worse since the server will yield indefinitely, waiting for a response. Theoretically you can invoke in a separate thread via coroutines.
```lua local client = game:GetService("Players").LocalPlayer;
function rf.OnClientInvoke() --// no player here return client:GetMouse().Hit; --// server probably needs the mouse hit end ```
lua
game:GetService("Players").PlayerAdded:Connect(function(client)
wait(4);
local hit = rf:InvokeClient(client);
print(hit);
end);
It is important that you pass the player you want to invoke. Or else Roblox won't know who to work with. Player is always the first argument when calling :InvokeClient
, and then anything else afterwards
```lua rf:InvokeClient(client, ...) rf.OnClientInvoke(...) -- notice no player, it's a mistake to add it here
Generally you would use remote functions client -> server when the client needs to get something only the server can access. Like maybe you have some stats stored on the server and the client needs them. You would rarely use server -> client, but a usecase would be the other way around, the server requesting something only the client can see, like the mouse target for example.