Replication handles continuous state - properties that change over time like position, health or score. But games also need one-shot events: a player fires a weapon, sends a chat message or triggers an ability. Remote Procedure Calls (RPCs) fill this gap by letting one client invoke a function on other clients without storing anything in the sync buffer.
RPCs are fire-and-forget - they are delivered once and not retained. If a client joins after an RPC was sent, it will not receive that call. For state that must survive late joins, use replicated properties instead.
Fusion RPCs are sent using fusion.rpc(), either to a specific player or to all players. RPCs are received as events.
-- set target_player to 0 to broadcast to all players
local target_player = 0
local target_object = 0
local event = hash("chat_message")
local data = { text = "Hello" }
fusion.rpc(target_player, target_object, event, data)
fusion.on_event(function(self, event_id, data)
if event_id == fusion.EVENT_RPC then
print(data.event) -- "chat_message"
print(message.text) -- "Hello"
end
end)
It is possible to target a specific player, all players (broadcast) or the owner of an object.
-- broadcast to all players
local target_player = 0
local target_object = 0
local event = hash("chat_message")
local data = { text = "Hello" }
fusion.rpc(target_player, target_object, event, data)
-- send to a specific player
local target_player = 1234
local target_object = 0
local event = hash("chat_message")
local data = { text = "Hello" }
fusion.rpc(target_player, target_object, event, data)
-- send to the owner of an object
local target_player = fusion.OBJECT_OWNER_PLAYER_ID
local target_object = 1234
local event = hash("chat_message")
local data = { text = "Hello" }
fusion.rpc(target_player, target_object, event, data)
All incoming RPCs are received as events of type fusion.EVENT_RPC in the fusion.on_event listener:
fusion.on_event(function(self, event_id, data)
if event_id == fusion.EVENT_RPC then
print(data.event) -- "chat_message"
print(message.text) -- "Hello"
end
end)
RPCs can also be received as Defold messages. An RPC targeting the owner of an object is sent as a Defold message to the game object associated with the object. Broadcast and player targeted RPCs can be subscribed to and will in such a case be received as Defold messages by the subscribing game objects:
function init(self)
fusion.subscribe_rpc(hash("some_message"))
end
function final(self)
fusion.unsubscribe_rpc(hash("some_message"))
end
function on_message(self, message_id, message, sender)
if message_id == hash("some_message") then
pprint(message)
end
end