Awaitable Rpc
Awaitable RPCs return a value from the server back to the calling client using async/await. The client sends a request and awaits the server's response in a single async method call.
How it works
When you call an awaitable RPC, PurrNet attaches a unique request ID to the outgoing packet. The server executes the method, packages the return value with the original request ID, and sends a reply packet back to the caller only. The caller's await completes when that reply arrives, and the Task<T> resolves to the server's return value.
From the programmer's perspective it looks like a normal async method call — no callbacks, no manual request/response correlation. You can return values from the server to the client without a separate callback or response RPC.
Declaration syntax
Mark the method with [ServerRpc] (or [TargetRpc]) and change the return type from void to Task<YourType>. PurrNet's source generator handles the rest.
using PurrNet;
using System.Threading.Tasks;
using UnityEngine;
public class LootRoller : NetworkBehaviour
{
// The return type IS the response type — no separate callback needed.
[ServerRpc(requireOwnership: true)]
public async Task<LootResult> CmdRollLoot(int chestId)
{
// This entire body runs on the server.
var chest = ChestRegistry.Get(chestId);
if (chest == null || chest.isLooted)
return new LootResult { success = false };
var item = LootTable.Roll(chest.tier, Random.Range(0, int.MaxValue));
chest.isLooted = true;
await chest.PlayOpenAnimation(); // server-side async work is fine
return new LootResult
{
success = true,
itemId = item.id,
quantity = item.quantity,
rarity = item.rarity,
};
}
}
[System.Serializable]
public struct LootResult : IPackedAuto
{
public bool success;
public int itemId;
public int quantity;
public string rarity;
}Calling an awaitable RPC from the client
using PurrNet;
using System;
using System.Threading.Tasks;
using UnityEngine;
public class ChestInteraction : NetworkBehaviour
{
[SerializeField] private LootRoller _roller;
public async void OnInteract(int chestId)
{
if (!isOwner) return;
// Show a spinner while we wait for the server
UI.ShowLoadingSpinner(true);
try
{
LootResult result = await _roller.CmdRollLoot(chestId);
if (result.success)
{
InventoryManager.AddItem(result.itemId, result.quantity);
UI.ShowLootPopup(result.itemId, result.rarity);
}
else
{
UI.ShowMessage("That chest is already empty.");
}
}
catch (TimeoutException)
{
UI.ShowMessage("Server did not respond. Try again.");
}
catch (OperationCanceledException)
{
// Player disconnected or scene unloaded during the await
}
finally
{
UI.ShowLoadingSpinner(false);
}
}
}Handling timeouts
If the server does not respond (for example, the object is despawned during the call), the Task throws a TimeoutException after PurrNet's default RPC timeout. Wrap awaitable RPC calls in try/catch to handle this gracefully. You can also pass a CancellationToken to cancel early if the player leaves the screen.
When to use each approach
| Parameter | Type | Default | Description |
|---|---|---|---|
Awaitable RPC | Task<T> | — | Client sends a request, suspends via await, and resumes when the server replies with a return value. One-to-one request/response. |
ObserversRpc + callback | void + event | — | Server pushes results to all observers. No built-in request ID. Better for broadcasting results to multiple clients simultaneously. |
SyncVar poll | SyncVar<T> | — | Server writes the value; client reads it on the next sync cycle. Best for state that must always be visible, not a one-time query. |
Situational example — server-side matchmaking query
Awaitable RPCs are ideal for any client query that requires a confirmed answer from the server before the client can proceed — skill checks, trade confirmations, leaderboard lookups.
using PurrNet;
using System.Threading.Tasks;
public class MatchmakingClient : NetworkBehaviour
{
[ServerRpc(requireOwnership: true)]
public async Task<MatchResult> CmdFindMatch(GameMode mode, int mmr)
{
// Server queries its matchmaking pool and responds when a slot is found
var slot = await MatchmakingService.FindSlot(mode, mmr);
return new MatchResult
{
found = slot != null,
lobbyCode = slot?.lobbyCode ?? string.Empty,
serverIp = slot?.ip ?? string.Empty,
serverPort = slot?.port ?? 0,
};
}
// ------- Caller side -------
public async void StartSearching(GameMode mode, int localMmr)
{
searchButton.interactable = false;
statusLabel.text = "Searching...";
try
{
var result = await CmdFindMatch(mode, localMmr);
if (result.found)
ConnectToServer(result.serverIp, result.serverPort, result.lobbyCode);
else
statusLabel.text = "No match found. Try again later.";
}
catch
{
statusLabel.text = "Connection error.";
}
finally
{
searchButton.interactable = true;
}
}
}Don't block the game loop
Update() or any per-frame callback creates a new pending request every frame. Only await RPCs from one-shot handlers (button clicks, trigger events, coroutines). Use a guard flag or disable the trigger until the previous await completes.UniTask support
UniTask<T> instead of Task<T> for zero-allocation async without the overhead of the standard TPL scheduler. Add the PurrNet-UniTask bridge package to your project to enable this.