RemoteFunctions (遠程函數)

Image 1
Roblox Studio

示例: Server RemoteFunction (伺服器遠程函數)

local replicatedStorage = game:GetService("ReplicatedStorage")
local remoteFunction = replicatedStorage:WaitForChild("RemoteFunction")

-- Function to handle when the remote function is invoked by the client
remoteFunction.OnServerInvoke = function(player, data)
	print(player.Name .. " invoked the function with data: " .. data)
	-- Process the data and return a response
	local response = "Received your data: " .. data
	return response
end
local replicatedStorage = game:GetService("ReplicatedStorage")
local remoteFunction = replicatedStorage:WaitForChild("RemoteFunction")

-- Function to invoke the remote function on the server
local result = remoteFunction:InvokeServer("Client to Server Data")
print("Server response: " .. result)
Image 1
Roblox Studio

示例: Client RemoteFunction (客戶端遠程函數)

local replicatedStorage = game:GetService("ReplicatedStorage")
local remoteFunction = replicatedStorage:WaitForChild("RemoteFunction")


-- Function to handle when the remote function is invoked by the server
remoteFunction.OnClientInvoke = function(data)
	print("Server invoked with data: " .. data)
	-- Process the data and return a response
	local response = "Client processed the data: " .. data
	return response
end
local replicatedStorage = game:GetService("ReplicatedStorage")
local remoteFunction = replicatedStorage:WaitForChild("RemoteFunction")


-- Function to handle when a player joins the game
local function onPlayerAdded(player)
	-- Invoke the client's RemoteFunction
	local result = remoteFunction:InvokeClient(player, "Server to Client Data")
	print("Client response: " .. result)
end

-- Connect the function to the PlayerAdded event
game.Players.PlayerAdded:Connect(onPlayerAdded)
Image 1
Roblox Studio