Session host migration
Learn about changing session ownership, including host election and data migration.
Read time 2 minutesLast updated 14 hours ago
In the sessions system, migration involves two aspects: host election, and data migration. The session system exposes to notify you about changes in session ownership and migration status:
- is raised when a new host is elected.
ISession.SessionHostChanged - is raised when data migration has completed.
ISession.SessionMigrated
Host election
Host election allows changing the session’s host. The current host can start this by updating the session’s assigned host ID. For the change to take effect, save all session properties so the update propagates to all participants.Data migration
Use host data migration to keep a client-hosted session running after the host is lost. This supports both voluntary and involuntary interruptions, such as network disconnections, power failures, or the host quitting the application.
Enable host data migration for a session by calling
WithHostMigrationIMigrationDataHandlerIMigrationDataHandler
Use the
WithHostMigration- Configure the interval for automatic Netcode snapshot generation.
- Set a timeout for snapshot uploads.
- Provide a custom if
IMigrationDataHandlerdoesn’t fit your use case.EntitiesMigrationDataHandler - Defaults: a 3-second snapshot interval and a 5-second upload timeout.
GetHostMigrationDataAsyncSetHostMigrationDataAsyncIMigrationDataHandlerUsing Relay
Added optional parameterpreserveRegionRelayOptionsWithRelayNetworkStartRelayNetworkExamples
Example: Creating a custom IMigrationData
Implement a data migration handler.Use the custom implementation with the sessions.public class CustomDataHandler : IMigrationDataHandler{ public byte[] Generate() { // implement a process to serialize data based on the network component in the scene / world return new byte[42]; } public void Apply(byte[] migrationData) { // implement a process to de-serialize data and apply in current scene / server world Assert.AreEqual(42, migrationData.Length); }}
public Task CreateOrJoinSessionWithDataMigartionEnabled(string sessionId){ var sessionOptions = new SessionOptions().WithHostMigration(migrationDataHandler: new CustomDataHandler()); var session = await MultiplayerService.Instance.CreateOrJoinSessionAsync(sessionId, options)}
Example: Electing a new Host
The following code snippet demonstrates how to elect a givenplayerAfter setting thepublic Task ElectPlayerAsHostAsync(string playerId){ _session.AsHost().Host = player.Id; return _session.AsHost().SavePropertiesAsync();}
session