PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

OnServerInvoke

RemoteFunction

Tuple

The OnServerInvoke event fires the bound functions in Scripts when RemoteFunction/InvokeServer is called by the server from a LocalScript. When the bound function returns, the returned values are sent back to the client.

This is used to retrieve remote events fired by the client and intended for the server. This event is in place to provide a method for communicating between the client and server, which is well documented in [this][1] article.

To fire from the server to the client, you should use RemoteFunction/InvokeClient and RemoteFunction/OnClientInvoke.

Note

  • Binding a function to OnServerInvoke is done with the assignment operator =, and not with an event. That is because OnServerInvoke is a callback and expects a function to be assigned to it. When the RemoteFunction is invoked, it will execute the function that was assigned to the onInvoke function.

  • Only one function can be assigned to OnServerInvoke at a time. If multiple functions are assigned, only the last function to be assigned will be used.

Parameters

Name Type Default Description

The Player corresponding to the client where the RemoteFunction/InvokeServer function call originated from.

Arguments passed to RemoteFunction/InvokeServer are passed to the function.

Expected Return Type

Return Type Summary

Values returned by the function are returned by RemoteFunction/InvokeServer (back to the client).


Code Samples


RemoteFunctions: Client to Server

When a client wants to use a remote function, it will invoke the server with the RemoteFunction/InvokeServer function within a LocalScript.

The server listens for this function to be invoked by binding a function to RemoteFunction/OnServerInvoke using the assignment operator =, and not with an event within a Script. When the server is invoked, it will execute the bound function.

-- LocalScript
 
local ReplicatedStorage = game:GetService("ReplicatedStorage")
 
local createPartRequest = ReplicatedStorage:WaitForChild("CreatePartRequest")
 
local newPart = createPartRequest:InvokeServer()
print("The server created this part for me:", newPart)


-- ==================================================


-- Script
 
local ReplicatedStorage = game:GetService("ReplicatedStorage")
 
local createPartRequest = Instance.new("RemoteFunction")
createPartRequest.Parent = ReplicatedStorage
createPartRequest.Name = "CreatePartRequest"
 
local function onCreatePartRequested(player)
	print(player.Name, "wants to create a new part")
	local newPart = Instance.new("Part")
	newPart.Parent = game.Workspace
	return newPart
end
 
createPartRequest.OnServerInvoke = onCreatePartRequested