Common mistakes with RemoteFunctions
Posted on October 6, 2014 by Merely
Networking is complicated, and there are a few mistakes that people make when using RemoteFunctions. Here are the two most common.
Passing references to objects in ServerStorage
I've seen numerous developers write code like this recently:
Server script:
RemoteFunction.OnServerInvoke = function(player, carName) return game.ServerStorage:FindFirstChild(carName) end
Local script:
local car = RemoteFunction:InvokeServer("Corvette") print(car) --> nil
Since the object is located in ServerStorage, it won't be replicated to the client. If you want the object to be accessible to the client, it needs to be parented to Workspace or ReplicatedStorage or another service that is accessible to clients.
Errors in RemoteFunctions are sent back to the client
If you have a RemoteFunction that performs an action that may throw an error, and you don't catch the error, it will be sent back to the client.
For example, if you have a game that uses HttpService to hit your web server, and for some reason one of the requests throws an error, the website's URL will be sent back to the client and will be visible in the Developer console.
RemoteFunction.OnServerInvoke = function(player) -- local contents = game:GetService("HttpService"):GetAsync("http://www.this-site-has-an-error.com/") return contents end
Local Console:
To prevent this, you should wrap your code in a pcall (protected call) so that errors in your RemoteFunction won't be sent back to the client.
RemoteFunction.OnServerInvoke = function(player) local success, err = pcall(function() local contents = game:GetService("HttpService"):GetAsync("http://www.this-site-has-an-error.com/") return contents end) -- `success` is a bool (true/false) that is false when the function in the pcall has errored if not success then -- If there is an error, a second value is returned, the error that occurred print("An error!", err) -- We also return here, so the function stops here and doesn't continue on return end -- If `success` is true, then any values it returns will be passed after the `success` bool return err -- Note, this isn't actually an error, but instead `contents` end
Commentary
Leave a Comment