Interface IVirooNetworkingApi
- Namespace
- Viroo.Api.Networking
- Assembly
- Viroo.dll
Provides access to networking-related features within Viroo.
public interface IVirooNetworkingApi
Remarks
The IVirooNetworkingApi acts as the central entry point for managing network connectivity and synchronized object interactions in a Viroo session. It unifies multiple networking operations under a single interface, allowing developers to monitor connection states, handle session properties, and manage authority over dynamic objects.
Typical networking features exposed by this API include:
- Connection lifecycle events – subscribe to events such as
OnConnected,OnDisconnected,OnReconnecting, andOnReconnectedto react to changes in network state. - Error handling – receive detailed error information through
OnConnectionErrorfor troubleshooting connectivity issues. - Session property updates – track changes in session properties via
OnSessionPropertyValueChangedandOnSessionPropertyRemoved. - Connection state queries – check flags such as
IsConnecting,IsConnected,IsDisconnecting,IsInitialized, andIsReconnectingto determine the current networking status. - Object management – create and destroy dynamic objects in the session using
CreateDynamicObject,DestroyObject, andDestroyObjects. - Authority control – request or release authority over networked objects with
RequestObjectAuthority,RequestObjectsAuthority,LeaveObjectAuthority, andLeaveObjectsAuthority. - Synchronized execution – leverage
IConditionalRunnerandISynchronizedRunnerfor coordinated actions across the network.
VirooApi.Instance.Networking() and
provides both high-level control (e.g., managing connection states) and low-level
access to object authority and synchronization mechanisms.
Properties
ConditionalRunner
Gets the conditional runner used to coordinate role-based execution across clients (leader vs. non-leader).
IConditionalRunner ConditionalRunner { get; }
Property Value
- IConditionalRunner
An Virtualware.Networking.TaskRunner.Conditional.IConditionalRunner that provides helpers to run code only on the leader, only on non-leader clients, or on both with separate execution paths.
Remarks
In this networking model there is no dedicated server entity; instead, exactly one client acts as the leader. The Virtualware.Networking.TaskRunner.Conditional.IConditionalRunner simplifies writing authority-like logic by exposing:
- Virtualware.Networking.TaskRunner.Conditional.IConditionalRunner.IsLeader to check if the current client is the leader.
- Virtualware.Networking.TaskRunner.Conditional.IConditionalRunner.RunIfLeader(System.Action) / Virtualware.Networking.TaskRunner.Conditional.IConditionalRunner.RunIfLeader(System.Func<System.Threading.Tasks.Task>) to execute only on the leader.
- Virtualware.Networking.TaskRunner.Conditional.IConditionalRunner.RunIfNotLeader(System.Action) / IConditionalRunner.RunIfNotLeader(Func<.Task>) to execute only on non-leader clients.
- Virtualware.Networking.TaskRunner.Conditional.IConditionalRunner.Run(System.Action, System.Action) / Virtualware.Networking.TaskRunner.Conditional.IConditionalRunner.Run(System.Func<System.Threading.Tasks.Task>, System.Func<System.Threading.Tasks.Task>) to run leader and non-leader branches in one call.
IsConnected
Gets a value indicating whether the local client is currently connected to the network session.
bool IsConnected { get; }
Property Value
Remarks
This property reflects whether an active connection to the network session exists. It is set to true once the OnConnected event is raised, and set back to false if the client disconnects (OnDisconnected) or fails to reconnect (OnReconnecting/OnReconnected).
Example:
if (VirooApi.Instance.Networking().IsConnected)
{
Debug.Log("Client is online and connected.");
}
else
{
Debug.Log("Client is offline.");
}
IsConnecting
Gets a value indicating whether the local client is currently attempting to connect to the network session.
bool IsConnecting { get; }
Property Value
Remarks
This property is useful to check if the system is in a transitional state between being disconnected and connected.
Example:
if (VirooApi.Instance.Networking().IsConnecting)
{
Debug.Log("Connecting to the session...");
}
IsDisconnecting
Gets a value indicating whether the local client is currently disconnecting from the network session.
bool IsDisconnecting { get; }
Property Value
Remarks
This property is true while the disconnection process is ongoing, typically between the time the client initiates a disconnect request and when the OnDisconnected event is raised.
Example:
if (VirooApi.Instance.Networking().IsDisconnecting)
{
Debug.Log("Client is disconnecting...");
}
IsInitialized
Gets a value indicating whether the networking system has been initialized.
bool IsInitialized { get; }
Property Value
Remarks
This property indicates whether the networking subsystem is ready for use.
Example:
if (!VirooApi.Instance.Networking().IsInitialized)
{
Debug.LogWarning("Networking is not initialized yet.");
return;
}
IsReconnecting
Gets a value indicating whether the client is currently attempting to reconnect after a disconnection.
bool IsReconnecting { get; }
Property Value
Remarks
This property is true when the client has lost its connection and is in the process of trying to reestablish it. It is reset to false once the reconnection succeeds (OnReconnected is raised) or ultimately fails (OnConnectionError may be raised).
Example:
if (VirooApi.Instance.Networking().IsReconnecting)
{
Debug.Log("Reconnecting to the session...");
}
SynchronizedRunner
Gets the synchronized runner that coordinates execution of work across all clients.
ISynchronizedRunner SynchronizedRunner { get; }
Property Value
- ISynchronizedRunner
An Virtualware.Networking.TaskRunner.Synchronized.ISynchronizedRunner that allows submitting actions or tasks to be executed on every connected client (including the caller), while awaiting until all clients complete or the operation times out.
Remarks
The Virtualware.Networking.TaskRunner.Synchronized.ISynchronizedRunner is used when you need to ensure that a piece of logic is executed consistently on all participants in the session. It blocks until every client reports completion, or until the specified timeout is reached.
The returned result (Virtualware.Networking.TaskRunner.Synchronized.SynchronizedRunResults) is a flag indicating where the work successfully ran:- Virtualware.Networking.TaskRunner.Synchronized.SynchronizedRunResults.RanLocally – executed on this client.
- Virtualware.Networking.TaskRunner.Synchronized.SynchronizedRunResults.RanRemotely – executed on all remote client.
- Virtualware.Networking.TaskRunner.Synchronized.SynchronizedRunResults.RanByAll – executed on local and all remotes.
- Virtualware.Networking.TaskRunner.Synchronized.SynchronizedRunResults.None – no client completed before the timeout.
Methods
ClearSessionProperty(string)
Removes a server-side Session Property identified by the specified key.
Task<SessionPropertyOperationResponse> ClearSessionProperty(string propertyKey)
Parameters
propertyKeystringThe unique key of the property to remove. Keys are scoped to the current session and must be non-empty.
Returns
- Task<SessionPropertyOperationResponse>
A Networking.Messages.SessionPropertyOperationResponse describing the result of the deletion request. Check Networking.Messages.MessageResponse.Success and Networking.Messages.MessageResponse.ErrorCode for the overall status, and inspect Networking.Messages.SessionPropertyOperationResponse.Data for per-property operation details.
Remarks
This method permanently deletes a Session Property from the server’s property dictionary for the current session. Once removed, the property key will no longer appear in subsequent GetSessionProperty(string) calls, and any listeners subscribed to OnSessionPropertyRemoved will receive a removal notification.
Behavior:
- If the property exists, the entry is removed and a corresponding Networking.Messages.SessionPropertyOperationResponseData will be returned with Networking.Messages.SessionPropertyOperationResponseData.Success set to true.
- If the property does not exist, the operation still completes, but the per-entry Networking.Messages.SessionPropertyOperationResponseData.Success is false and may include Networking.Messages.SessionPropertyOperationResponseData.ErrorType.KeyDoesNotExist in its Networking.Messages.SessionPropertyOperationResponseData.ErrorCode.
- If the session is invalid or the client is unauthenticated, the overall response will have Networking.Messages.MessageResponse.Success set to false and Networking.Messages.MessageResponse.ErrorCode may correspond to Networking.Messages.SessionPropertyOperationResponse.ErrorType.NotAuthenticated or Networking.Messages.SessionPropertyOperationResponse.ErrorType.NotInSession.
Usage notes:
- Use this method instead of setting the property value to null when you intend to fully remove it from the session dictionary.
- Other clients in the same session will receive an event via OnSessionPropertyRemoved indicating that the property was deleted.
- This operation affects only the current session scope and does not modify persisted user or application settings.
Error handling: Always verify both:
- Networking.Messages.MessageResponse.Success and Networking.Messages.MessageResponse.ErrorCode — for transport/session validity.
- The individual entry in Networking.Messages.SessionPropertyOperationResponse.Data — for key-specific success or failure.
CreateDynamicObject(string, Vector3, Quaternion, bool, bool, string)
Task<UnityCreateSingleSessionObjectResponse> CreateDynamicObject(string resourceIdentifier, Vector3 position, Quaternion rotation, bool requestAuthority, bool isPersistent, string objectId = "")
Parameters
resourceIdentifierstringpositionVector3rotationQuaternionrequestAuthorityboolisPersistentboolobjectIdstring
Returns
- Task<UnityCreateSingleSessionObjectResponse>
CreateNetworkVariable<T>(string, T, bool)
NetworkVariable<T> CreateNetworkVariable<T>(string variableIdentifier, T defaultValue, bool resetValueOnSceneChange = true)
Parameters
Returns
- NetworkVariable<T>
Type Parameters
T
DestroyObject(INetworkObject)
Destroys a networked object from the session.
Task<DestroySessionObjectResponse> DestroyObject(INetworkObject networkObject)
Parameters
networkObjectINetworkObjectThe Virtualware.Networking.Client.INetworkObject to destroy. This must be an object that currently exists in the networked session.
Returns
- Task<DestroySessionObjectResponse>
A task that completes with a Networking.Messages.DestroySessionObjectResponse, which reports whether the destruction succeeded and, if not, which error occurred.
Remarks
This method removes the specified object from the session so that it is no longer synchronized across connected clients. The returned Networking.Messages.DestroySessionObjectResponse provides:
- Networking.Messages.MessageResponse.Success — true if the destruction request was successful.
- Networking.Messages.DestroySessionObjectResponse.Id — Identifier of the destroy request.
- Networking.Messages.DestroySessionObjectResponse.DestroySessionObjectsData — Details about the destroyed object(s).
- Networking.Messages.DestroySessionObjectResponse.ErrorTypes — A flagged enum describing specific error conditions.
Error codes (from Networking.Messages.DestroySessionObjectResponse.ErrorTypes):
- ObjectDoesNotExist — The specified object could not be found in the session.
- Unauthorized — The client does not have permission to destroy the object (e.g., no authority or not the owner of a persistent object).
- NotAuthenticated — The client is not authenticated in the session.
- NotInSession — The client is not part of the session and cannot destroy objects.
Example:
// Destroy a network object previously created
DestroySessionObjectResponse destroyResponse = await VirooApi.Instance.Networking().DestroyObject(myNetworkObject);
if (destroyResponse.Success)
{
Debug.Log("Object successfully destroyed.");
}
else
{
Debug.LogError($"Failed to destroy object. Error: {destroyResponse.ErrorCode}, " +
$"Flags: {destroyResponse.DestroySessionObjectsData}");
}
DestroyObjects(IEnumerable<INetworkObject>)
Destroys multiple networked objects from the session in a single request.
Task<DestroySessionObjectResponse> DestroyObjects(IEnumerable<INetworkObject> networkObjects)
Parameters
networkObjectsIEnumerable<INetworkObject>A collection of Virtualware.Networking.Client.INetworkObject instances to destroy. Each object must currently exist in the networked session.
Returns
- Task<DestroySessionObjectResponse>
A task that completes with a Networking.Messages.DestroySessionObjectResponse, which summarizes the outcome of the destruction request for all specified objects.
Remarks
This method is the batch counterpart to DestroyObject(INetworkObject). It allows removing several objects in one operation, reducing the number of round-trips to the networking layer.
The returned Networking.Messages.DestroySessionObjectResponse includes:- Networking.Messages.MessageResponse.Success — true if all objects were destroyed successfully.
- Networking.Messages.DestroySessionObjectResponse.DestroySessionObjectsData — Detailed results for each object, including whether it was destroyed and any error codes.
- Networking.Messages.DestroySessionObjectResponse.ErrorTypes — Flagged errors that may indicate partial failure (e.g., some objects could not be destroyed because they did not exist).
GetSessionProperty(string)
Retrieves the current value of a server-side Session Property identified by the specified key.
Task<SessionPropertyOperationResponse> GetSessionProperty(string propertyKey)
Parameters
propertyKeystringThe unique key of the property to read. Keys are scoped to the active session and must be non-empty.
Returns
- Task<SessionPropertyOperationResponse>
A Networking.Messages.SessionPropertyOperationResponse describing the outcome of the retrieval. Inspect Networking.Messages.MessageResponse.Success and Networking.Messages.MessageResponse.ErrorCode for the overall request status. Then read the (typically single) entry in Networking.Messages.SessionPropertyOperationResponse.Data for per-key details, including the returned Networking.Messages.SessionPropertyOperationResponseData.Value (which may be null).
Remarks
Session Properties are stored on the server as a dictionary of String keys to object values and are accessed via discrete get/set/clear calls. This method queries a single key and returns per-key details in Networking.Messages.SessionPropertyOperationResponse.Data.
Behavior:
- If the property exists and is readable, the entry’s Networking.Messages.SessionPropertyOperationResponseData.Success is true and Networking.Messages.SessionPropertyOperationResponseData.Value holds a Networking.Messages.MessageParam instance representing the stored value.
- If the key does not exist, the entry’s Networking.Messages.SessionPropertyOperationResponseData.Success is false and Networking.Messages.SessionPropertyOperationResponseData.ErrorType.KeyDoesNotExist may be indicated via Networking.Messages.SessionPropertyOperationResponseData.ErrorCode.
- Networking.Messages.SessionPropertyOperationResponseData.Value can be null to denote an explicit null payload stored under the key. This differs from the key being absent.
- The per-entry Networking.Messages.SessionPropertyOperationResponseData.Operation will be the corresponding read operation.
About Networking.Messages.MessageParam: The value is wrapped in Networking.Messages.MessageParam to preserve transport semantics and type-agnostic handling.
- Access the raw payload through Networking.Messages.MessageParam.UntypedValue. This may be a String, numeric type, bool, or null depending on what was stored.
- Equality and hashing in Networking.Messages.MessageParam are based on Networking.Messages.MessageParam.UntypedValue; two wrappers are equal if their underlying values are equal.
- When complex objects are stored, they are commonly serialized to String (e.g., JSON) on set and deserialized on read.
Error handling: Always check both levels:
- Overall request: Networking.Messages.MessageResponse.Success / Networking.Messages.MessageResponse.ErrorCode (e.g., not authenticated or not in session).
- Per-property entry in Networking.Messages.SessionPropertyOperationResponse.Data: Networking.Messages.SessionPropertyOperationResponseData.Success, Networking.Messages.SessionPropertyOperationResponseData.ErrorCode, and Networking.Messages.SessionPropertyOperationResponseData.PropertyKey.
Usage notes:
- For structured payloads, deserialize Networking.Messages.MessageParam.UntypedValue (commonly a JSON String) into your DTO.
- When reading many keys, prefer the corresponding batch API to reduce round-trips.
- Changes performed by other clients are surfaced through OnSessionPropertyValueChanged events; cache cautiously and invalidate on notifications.
RequestObjectAuthority(INetworkObject)
Requests authority over a specific network object for the current client.
Task<SessionObjectAuthorityResponse> RequestObjectAuthority(INetworkObject networkObject)
Parameters
networkObjectINetworkObjectThe Virtualware.Networking.Client.INetworkObject to request authority on.
- The object must be
createdin the current session. - If the client already holds authority, the call is idempotent and succeeds immediately.
- The object must be
Returns
- Task<SessionObjectAuthorityResponse>
An asynchronous task producing a Networking.Messages.SessionObjectAuthorityResponse describing the result:
- SessionObjectAuthorityResponse.Succeeded will contain the object if authority was granted.
- SessionObjectAuthorityResponse.Failures will contain the object if authority could not be acquired, with a reason.
- SessionObjectAuthorityResponse.IsSuccess will indicate if the authority request was successful.
Remarks
- This operation may fail if authority is already taken and
onlyWhenAuthorityIsFreeis set totrue. - Clients should inspect the response and handle failures gracefully.
RequestObjectsAuthority(IEnumerable<INetworkObject>)
Requests authority over one or more networked objects for the current client.
Task<SessionObjectAuthorityResponse> RequestObjectsAuthority(IEnumerable<INetworkObject> networkObjects)
Parameters
networkObjectsIEnumerable<INetworkObject>A collection of Virtualware.Networking.Client.INetworkObject instances for which the local client wants to request authority.
Returns
- Task<SessionObjectAuthorityResponse>
A task that completes with a Networking.Messages.SessionObjectAuthorityResponse, which summarizes the outcome of the authority request for all specified objects.
Remarks
This method allows a client to claim authority over several objects in a single call, instead of issuing multiple individual requests.
The returned Networking.Messages.SessionObjectAuthorityResponse reports:- Networking.Messages.MessageResponse.Success — true if all authority requests succeeded.
- Error details for each object, such as unauthorized requests or objects not found.
- The updated authority and ownership state for each affected object.
SetSessionProperty<T>(string, T)
Task<SessionPropertyOperationResponse> SetSessionProperty<T>(string propertyKey, T value)
Parameters
propertyKeystringvalueT
Returns
- Task<SessionPropertyOperationResponse>
Type Parameters
T
Events
OnConnected
Occurs when the local client successfully connects to the network session.
event EventHandler OnConnected
Event Type
Remarks
This event is raised once a network connection has been established. At this point, the client is considered online and ready to interact with other participants or services in the session.
Behavior:
- This event is fired only once per successful connection attempt.
- It will not be raised again unless the client disconnects and reconnects.
Usage notes:
- Subscribe to this event to initialize gameplay systems, synchronize state, or update UI elements indicating connectivity.
- Consider pairing this event with OnDisconnected and OnReconnected for full lifecycle handling.
Example:
VirooApi.Instance.Networking().OnConnected += (sender, args) =>
{
Debug.Log("Successfully connected to the session!");
};
OnConnectionError
Occurs when a connection-related error happens.
event EventHandler<ConnectionErrorEventArgs> OnConnectionError
Event Type
- EventHandler<ConnectionErrorEventArgs>
Remarks
This event is raised whenever the VIROO client fails to establish or maintain a connection, authenticate, or join a session. It provides detailed error information to allow applications to handle failures gracefully and inform the user.
Event arguments (Virtualware.Networking.Client.ConnectionErrorEventArgs):
- Virtualware.Networking.Client.ConnectionErrorEventArgs.ErrorType — Indicates the category of the error (e.g., authentication failure, timeout, network unreachable).
- Virtualware.Networking.Client.ConnectionErrorEventArgs.Message — A descriptive message explaining the cause or context of the error.
Behavior:
- This event is fired whenever a critical networking operation cannot be completed successfully.
- It may occur during initial connection attempts, session joins, or reconnection processes.
- No automatic retry is performed by this event; reconnection logic must be implemented by the client if desired.
Usage notes:
- Subscribe to this event to display error messages to the user, log diagnostic information, or trigger recovery workflows.
- Inspect Virtualware.Networking.Client.ConnectionErrorEventArgs.ErrorType to determine the appropriate corrective action (e.g., prompt for credentials, retry connection).
- Consider implementing exponential backoff or user-driven retry mechanisms for transient errors.
Example:
VirooApi.Instance.Networking().OnConnectionError += (sender, args) =>
{
Debug.LogError($"Connection error: {args.ErrorType} - {args.Message}");
ShowErrorUI(args.Message);
};
OnDisconnected
Occurs when the local client is disconnected from the network session.
event EventHandler OnDisconnected
Event Type
Remarks
This event is raised whenever the local client loses or closes its connection to the network session. Disconnections may occur intentionally (e.g., leaving the session) or unintentionally (e.g., network failure).
Behavior:
- This event is fired for all disconnection scenarios, including manual disconnects and unexpected network drops.
- After this event, the client is considered offline until a successful reconnection occurs.
Usage notes:
- Subscribe to this event to pause gameplay, show reconnection UI, or release network-dependent resources.
- Combine with OnReconnecting and OnReconnected for robust recovery workflows.
Example:
VirooApi.Instance.Networking().OnDisconnected += (sender, args) =>
{
Debug.Log("Disconnected from the session.");
ShowReconnectUI();
};
OnReconnected
Occurs when the local client has successfully reconnected to the network session after a disconnection.
event EventHandler OnReconnected
Event Type
Remarks
This event is raised once the client manages to restore the network connection following a disconnection. At this point, the session is considered online again, and gameplay or network-dependent systems can safely resume.
Behavior:
- This event is fired only after a successful reconnection following a previous disconnection.
- It indicates that the session is stable and ready for normal operations.
Usage notes:
- Subscribe to this event to resume gameplay, re-enable UI elements, or synchronize state with the server.
- Combine with OnDisconnected and OnReconnecting for full lifecycle handling.
Example:
VirooApi.Instance.Networking().OnReconnected += (sender, args) =>
{
Debug.Log("Successfully reconnected to the session!");
};
OnReconnecting
Occurs when the local client is attempting to reconnect to the network session.
event EventHandler OnReconnecting
Event Type
Remarks
This event is raised automatically when the client begins a reconnection attempt after losing its connection.
Behavior:
- This event signals the start of a reconnection attempt, which may succeed or fail.
- If successful, OnReconnected will be raised; if unsuccessful, OnConnectionError may occur.
Usage notes:
- Subscribe to this event to display loading indicators or disable network-dependent UI elements during reconnection.
- Consider implementing timeouts or retry limits for reconnection attempts.
Example:
VirooApi.Instance.Networking().OnReconnecting += (sender, args) =>
{
Debug.Log("Attempting to reconnect to the session...");
};
OnSessionPropertyRemoved
Occurs when a Session Property is removed from the server-side session dictionary, typically as a result of a successful ClearSessionProperty(string) call by any client.
event EventHandler<PropertyRemovedEventArgs> OnSessionPropertyRemoved
Event Type
- EventHandler<PropertyRemovedEventArgs>
Remarks
This event is raised whenever the VIROO server notifies connected clients that a property has been deleted from the shared session. It enables local systems to stay synchronized by cleaning up or resetting associated state without requiring explicit polling.
Event arguments (Virtualware.Networking.Client.Properties.PropertyRemovedEventArgs):
- Virtualware.Networking.Client.Properties.PropertyRemovedEventArgs.PropertyKey — The key of the property that was removed.
Behavior:
- This event is fired for all clients in the session whenever any participant successfully clears a Session Property.
- The event may also be raised locally for confirmation when the current client invokes ClearSessionProperty(string).
- No OnPropertyValueChanged event is emitted for deletions — only this one is triggered.
Usage notes:
- Subscribe to this event to remove local caches, UI bindings, or gameplay data associated with the deleted property key.
- Attempting to access the removed property with GetSessionProperty(string) after this event will return an error or an empty result.
OnSessionPropertyValueChanged
Occurs when a Session Property’s value is updated by any client in the current session.
event EventHandler<PropertyValueChangedEventArgs> OnSessionPropertyValueChanged
Event Type
- EventHandler<PropertyValueChangedEventArgs>
Remarks
This event is raised whenever the server broadcasts a property value update notification. It allows clients to react to state changes performed elsewhere in the session without the need for explicit polling via GetSessionProperty(string).
Event arguments (Virtualware.Networking.Client.Properties.PropertyValueChangedEventArgs):
- Virtualware.Networking.Client.Properties.PropertyValueChangedEventArgs.PropertyKey — The key of the property whose value changed.
- Virtualware.Networking.Client.Properties.PropertyValueChangedEventArgs.SenderClientId — The client ID of the peer that triggered the update.
- Virtualware.Networking.Client.Properties.PropertyValueChangedEventArgs.Value — The new property value serialized as a String. For complex data (e.g., JSON), the receiver must deserialize this string to reconstruct the original object.
Behavior:
- The event is fired for all clients in the same session when any of them invokes SetSessionProperty<T>(string, T) successfully.
- The event may also be raised locally as confirmation of a successful update performed by the same client.
- If a property is removed through ClearSessionProperty(string), this event is not triggered; instead, OnPropertyRemoved (if implemented) will be raised.
Usage notes:
- Subscribe to this event to keep local UI or simulation state synchronized with the shared session data.
- Always compare Virtualware.Networking.Client.Properties.PropertyValueChangedEventArgs.SenderClientId against your local client ID to avoid redundant updates when reacting to your own changes.
- Deserialize Virtualware.Networking.Client.Properties.PropertyValueChangedEventArgs.Value using the same format you used when storing the property (for example, JSON).