Steam Connection Workflow
Step-by-step guide to integrating PurrNet with Facepunch.Steamworks: offline boot, player identity, lobby creation, party management, and P2P game start.
This guide walks you through connecting PurrNet with Facepunch.Steamworksstep by step: booting the Steam client offline, fetching the playerโs Steam identity, creating a friends-only lobby, managing party slots, and finally handing the network connection off to PurrNet via Steam P2P transport so your game scene can load with everyone connected.
The game starts fully offline. SteamInitializer.Awake() calls SteamClient.Init() and stores the local player's name + SteamId. If Steam isn't running the game shows an offline warning but doesn't crash.
// SteamInitializer.cs (DontDestroyOnLoad)
void Awake() {
DontDestroyOnLoad(gameObject);
try {
SteamClient.Init(480); // your AppId
LocalSteamId = SteamClient.SteamId;
LocalPlayerName = SteamClient.Name;
onSteamReady?.Invoke();
} catch (Exception e) {
Debug.LogWarning("[Steam] " + e.Message);
onSteamFailed?.Invoke(); // show offline UI
}
}
void Update() => SteamClient.RunCallbacks();Prerequisites
- Unity 6 (or 2022 LTS) with PurrNet installed
- Facepunch.Steamworks package imported
- A valid Steamworks AppId (use
480for local testing โ Spacewar) - Steam client running on the developer machine
- PurrNetโs Steam transport added to your NetworkManager
480 (Spacewar) is only for development testing. Before shipping, replace it with your real AppId and ensure your steam_appid.txt file in the project root contains that AppId.Scene Architecture
The workflow spans three scenes. Keep SteamInitializer and SteamLobbyManager on DontDestroyOnLoad objects so they survive scene loads.
- Title / Boot Scene โ offline startup, Steam init, optional offline warning UI
- Main Menu Scene โ fetch player avatar, show lobby UI, create / join party
- Game Scene โ loaded by PurrNet after the host calls
SetGameServer(); all players arrive connected
Step 1 โ SteamInitializer (Title Scene)
Create a DontDestroyOnLoad GameObject in the Title scene and attach SteamInitializer. It calls SteamClient.Init() in Awake, stores the local SteamId + name, and exposes two UnityEvents for the title scene to react to.
using System;
using Steamworks;
using UnityEngine;
/// <summary>
/// Boots the Steamworks client on startup.
/// Attach to a DontDestroyOnLoad singleton.
/// </summary>
public class SteamInitializer : MonoBehaviour
{
public static SteamId LocalSteamId { get; private set; }
public static string LocalPlayerName { get; private set; } = "Player";
public static bool IsInitialized { get; private set; }
[SerializeField] private uint _appId = 480; // 480 = Spacewar (dev/test)
public event Action onSteamReady;
public event Action onSteamFailed;
void Awake()
{
DontDestroyOnLoad(gameObject);
try
{
SteamClient.Init(_appId);
LocalSteamId = SteamClient.SteamId;
LocalPlayerName = SteamClient.Name;
IsInitialized = true;
onSteamReady?.Invoke();
}
catch (Exception e)
{
Debug.LogWarning("[Steam] Init failed: " + e.Message);
onSteamFailed?.Invoke(); // show offline / retry UI
}
}
void Update()
{
// REQUIRED every frame โ dispatches pending Steam callbacks
if (IsInitialized)
SteamClient.RunCallbacks();
}
void OnDestroy() => SteamClient.Shutdown();
}// TitleSceneManager.cs
// Attach to a single GameObject in your Title / Boot scene.
using UnityEngine;
using UnityEngine.SceneManagement;
public class TitleSceneManager : MonoBehaviour
{
[SerializeField] private SteamInitializer _steamInit;
[SerializeField] private GameObject _offlineWarning;
[SerializeField] private string _mainMenuScene = "MainMenu";
void Awake()
{
_steamInit.onSteamReady += OnSteamReady;
_steamInit.onSteamFailed += OnSteamFailed;
}
void OnSteamReady()
{
// Hide any "Steam not running" UI
_offlineWarning.SetActive(false);
// Proceed to main menu โ fetch avatar here or after scene load
SceneManager.LoadScene(_mainMenuScene);
}
void OnSteamFailed()
{
// Show offline warning; player can retry or quit
_offlineWarning.SetActive(true);
}
}SteamClient.RunCallbacks() in Update(). Without it, none of the event callbacks (lobby member joined, game created, etc.) will ever fire.SteamInitializer API
| Parameter | Type | Default | Description |
|---|---|---|---|
SteamClient.Init(uint appId) | void | โ | Initialize the Steamworks client. Must be called once on the main thread before any other Steam API call. Throws if Steam is not running. |
SteamClient.SteamId | SteamId | โ | The local player's 64-bit Steam ID. Available immediately after Init(). |
SteamClient.Name | string | โ | The local player's Steam persona name. |
SteamClient.RunCallbacks() | void | โ | Must be called every frame (in Update) to dispatch pending Steam events and fire registered callbacks. |
SteamFriends.GetLargeAvatarAsync(id) | Task<Image?> | โ | Async fetch of the player's 184ร184 avatar image. Returns null if not cached; call in a try/catch. |
Step 2 โ Fetch Steam Player Data
Once onSteamReadyfires, load the Main Menu scene and immediately fetch the playerโs persona name and avatar. The name is available synchronously; the avatar requires an async call to SteamFriends.GetLargeAvatarAsync().
using Steamworks;
using Steamworks.Data;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Fetches the local player's Steam avatar and persona name.
/// Call FetchLocalPlayer() after SteamInitializer.onSteamReady fires.
/// </summary>
public class SteamPlayerFetcher : MonoBehaviour
{
[SerializeField] private RawImage _avatarImage;
[SerializeField] private Text _playerNameText;
public async void FetchLocalPlayer()
{
_playerNameText.text = SteamClient.Name;
try
{
Image? img = await SteamFriends
.GetLargeAvatarAsync(SteamClient.SteamId);
if (img.HasValue)
_avatarImage.texture = ConvertToTexture2D(img.Value);
}
catch (Exception e)
{
Debug.LogWarning("[Steam] Avatar fetch failed: " + e.Message);
}
}
// โโ Helper: Steamworks.Data.Image โ UnityEngine.Texture2D โโโโโโโโโโโโโโ
private static Texture2D ConvertToTexture2D(Image img)
{
var tex = new Texture2D((int)img.Width, (int)img.Height,
TextureFormat.ARGB32, false);
for (int x = 0; x < img.Width; x++)
for (int y = 0; y < img.Height; y++)
{
var pixel = img.GetPixel(x, y);
// Steam stores pixels top-down; Unity expects bottom-up
tex.SetPixel(x, (int)img.Height - y - 1,
new Color(pixel.r / 255f, pixel.g / 255f,
pixel.b / 255f, pixel.a / 255f));
}
tex.Apply();
return tex;
}
}img.Height - y - 1 flip in ConvertToTexture2D is mandatory โ omitting it produces an upside-down avatar.Step 3 โ Create and Join a Steam Lobby
SteamLobbyManager handles all lobby operations for both host and guest. The host calls CreateLobby(); guests are invited through Steam and their client auto-calls JoinLobby() when the invite is accepted.
using System;
using Steamworks;
using Steamworks.Data;
using UnityEngine;
/// <summary>
/// Creates, joins, and manages a Steam friends-only lobby.
/// Designed as a singleton used by both host and guest.
/// </summary>
public class SteamLobbyManager : MonoBehaviour
{
// โโ State โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
public Lobby CurrentLobby { get; private set; }
public bool IsHost { get; private set; }
[SerializeField] private int _maxPlayers = 4;
public event Action<Friend> onMemberJoined;
public event Action<Friend> onMemberLeft;
public event Action onGameStarting;
// โโ Unity lifecycle โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void OnEnable()
{
SteamMatchmaking.OnLobbyMemberJoined += HandleMemberJoined;
SteamMatchmaking.OnLobbyMemberLeave += HandleMemberLeft;
SteamMatchmaking.OnLobbyGameCreated += HandleGameCreated;
}
void OnDisable()
{
SteamMatchmaking.OnLobbyMemberJoined -= HandleMemberJoined;
SteamMatchmaking.OnLobbyMemberLeave -= HandleMemberLeft;
SteamMatchmaking.OnLobbyGameCreated -= HandleGameCreated;
}
// โโ Host: Create Lobby โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
public async void CreateLobby()
{
var result = await SteamMatchmaking.CreateLobbyAsync(_maxPlayers);
if (!result.HasValue)
{
Debug.LogError("[Steam] CreateLobby failed.");
return;
}
CurrentLobby = result.Value;
IsHost = true;
// Configure lobby metadata
CurrentLobby.SetFriendsOnly();
CurrentLobby.SetData("game", Application.productName);
CurrentLobby.SetData("version", Application.version);
CurrentLobby.SetData("host", SteamClient.Name);
Debug.Log($"[Steam] Lobby created: {CurrentLobby.Id}");
}
// โโ Guest: Join Lobby โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Usually called automatically by Steam rich-presence / invite acceptance
public async void JoinLobby(SteamId lobbyId)
{
var result = await SteamMatchmaking.JoinLobbyAsync(lobbyId);
if (!result.HasValue)
{
Debug.LogError("[Steam] JoinLobby failed.");
return;
}
CurrentLobby = result.Value;
IsHost = false;
}
// โโ Host only: change max player count after creation โโโโโโโโโโโโโโโโโโ
public void SetMaxPlayers(int count)
{
_maxPlayers = Mathf.Clamp(count, 2, 8);
if (IsHost && CurrentLobby.Id.IsValid)
CurrentLobby.MaxMembers = _maxPlayers;
}
// โโ Host only: signal everyone to start โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
public void StartGame()
{
if (!IsHost) return;
// Writing the host SteamId as the "game server" fires
// OnLobbyGameCreated on ALL connected members.
CurrentLobby.SetGameServer(SteamClient.SteamId);
}
// โโ Callbacks โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
void HandleMemberJoined(Lobby _, Friend f) => onMemberJoined?.Invoke(f);
void HandleMemberLeft (Lobby _, Friend f) => onMemberLeft?.Invoke(f);
void HandleGameCreated (Lobby _, uint __, ushort ___, SteamId ____) =>
onGameStarting?.Invoke();
}Lobby API Reference
| Parameter | Type | Default | Description |
|---|---|---|---|
SteamMatchmaking.CreateLobbyAsync(maxPlayers) | Task<Lobby?> | โ | Host creates a new Steam lobby with the given max-player count. Returns null on failure. |
lobby.SetFriendsOnly() | void | โ | Restricts the lobby to friends-only. Guests must receive an explicit invite. |
lobby.SetData(key, value) | void | โ | Stores arbitrary string metadata on the lobby, visible to all members. |
lobby.MaxMembers | int (set) | โ | Update max player count after creation. Changes take effect immediately. |
SteamMatchmaking.JoinLobbyAsync(lobbyId) | Task<Lobby?> | โ | Guest joins an existing lobby by ID. Usually called via the OnLobbyInvite or GameRichPresenceJoinRequested callback. |
lobby.SetGameServer(hostSteamId) | void | โ | Host signals all members that the game is starting. Fires OnLobbyGameCreated on every client. |
SteamMatchmaking.OnLobbyMemberJoined | event | โ | Fires on all lobby members when a new player joins. Use it to refresh the roster UI. |
SteamMatchmaking.OnLobbyMemberLeave | event | โ | Fires on all lobby members when a player leaves or is kicked. |
Interactive Lobby Simulator
Try it yourself โ simulate friends joining, set max players, mark everyone ready, and press Start Game to see the handoff flow.
Step 4 โ SteamNetworkBridge (PurrNet Handoff)
When the host calls lobby.SetGameServer(SteamClient.SteamId), Steam fires OnLobbyGameCreated on every member simultaneously. SteamNetworkBridge listens to the onGameStarting event from SteamLobbyManager and starts PurrNet accordingly: the host becomes the server, guests connect via Steam P2P.
using PurrNet;
using Steamworks;
using UnityEngine;
/// <summary>
/// Bridges Steam lobby signals to PurrNet startup.
/// Attach to the same GameObject as NetworkManager.
///
/// When the host calls lobby.SetGameServer():
/// Host โ starts PurrNet server + joins as client
/// Guest โ connects PurrNet to host's SteamId via Steam P2P
/// </summary>
public class SteamNetworkBridge : NetworkBehaviour
{
[SerializeField] private SteamLobbyManager _lobby;
[SerializeField] private NetworkManager _networkManager;
[SerializeField] private string _gameScene = "GameScene";
void OnEnable() => _lobby.onGameStarting += HandleGameStarting;
void OnDisable() => _lobby.onGameStarting -= HandleGameStarting;
// โโ Called on ALL clients when host fires SetGameServer() โโโโโโโโโโโโโ
void HandleGameStarting()
{
if (_lobby.IsHost)
{
// Host becomes the PurrNet server AND a client
_networkManager.StartServer();
_networkManager.StartClient();
}
else
{
// Guests connect to host via Steam P2P transport
// PurrNet's Steam transport uses the SteamId as the address
SteamId hostId = _lobby.CurrentLobby.Owner.Id;
_networkManager.Connect(hostId.ToString());
}
}
// โโ After server is running: load the game scene for all clients โโโโโโโ
protected override void OnSpawned(bool asServer)
{
if (asServer)
NetworkManager.LoadScene(_gameScene);
}
}NetworkManager.StartServer() on their machine, or (b) use a dedicated server. Plan for this before shipping.Best Practices
SteamInitializer and SteamLobbyManager on separate DontDestroyOnLoad GameObjects. Mixing them onto a single object makes it impossible to destroy the lobby without also destroying the Steam init state.SetData) for game version and mode before sending invites. Friends can read this from the invite overlay and decide whether to join before your server wastes a slot.SteamClient.Init() more than once per process. Unity will enter playmode and stop it many times in the editor โ guard Init with a static bool or check SteamClient.IsValid first.480 (Spacewar). Any live Steam player could accidentally join your lobby. Replace with your real AppId before any public build.