Session API
GraffityARCloudSession is the component that connects your AR Foundation scene to Graffity AR Cloud. It is the whole public surface: state, guidance, destinations, lifecycle and navigation commands, C# events and their UnityEvent twins.
Call every API on the Unity main thread. Use one session per AR Session and XR Origin.
Inspector fields
| Field | Description |
|---|---|
| AR Session / XR Origin | Your AR Foundation objects. Assigned automatically when the scene has exactly one of each. The XR Origin’s camera needs an ARCameraManager. |
| Map Roots | The GraffityARMapRoot of each section in this scene. The point-cloud browser and GameObject > XR > Graffity Map Root add roots for you. |
| Start On Enable | Start localizing when the component is enabled. Off by default. |
| Navigation Renderer | Optional route arrow renderer. See Navigation. |
| Auto Retry Localization | Retry failed localization automatically with backoff. On by default. |
| Advanced › Connection Timeout Seconds | First reply and settings fallback deadline; default 15 seconds. |
| Advanced › Response Timeout Seconds | Each later localization reply deadline; default 60 seconds. |
| Advanced › Tracking Timeout Seconds | Longest tracking loss before TrackingUnavailable; default 30 seconds. |
| Advanced › Maximum Consecutive Frame Failures | Failed captures before an attempt fails; default 3. |
| Events | UnityEvents for state, localization, failure and navigation. See Events. |
The access token and analytics project key are not on the component. They live in Project Settings > Graffity AR Cloud, shared by every scene. The session reads its settings once, when it initializes. To change them later, await session.ShutdownAsync(), edit them, and start again.
Configure from code
To use a token from your backend instead of the Project Settings token, set it before the session initializes:
session.AccessToken = tokenFromYourBackend;
session.StartSession();The SDK accepts the raw token or the Bearer <token> form. Setting AccessToken throws once the session is initialized. It is runtime state, so set it in Play Mode or in the player, not from an Editor script.
To bind scene references from code, call SetSceneReferences before initialization:
session.SetSceneReferences(arSession, xrOrigin, new[] { mapRoot });For all SDK options, pass a configuration before initialization. It replaces the Inspector’s SDK options and the Project Settings credentials, and keeps the assigned scene references:
session.Configure(new GraffityARCloudConfiguration(tokenFromYourBackend)
{
UserId = playerId,
LogClient = yourThreadSafeLogClient,
AnalyticsSampleRate = 0,
LocalizationOptions = new GraffityARLocalizationOptions { ResponseTimeoutSeconds = 60 },
});
session.StartSession();InitialLocation, Diagnostics, AnalyticsProjectKey and PreferredTransitionTypeId are also available. A usable InitialLocation can substitute for denied live GPS; it must meet the SDK’s freshness and accuracy limits. The session copies the options when you call Configure, so later changes to your object have no effect. Await ShutdownAsync() before configuring again.
session.ValidateSetup() returns a list of setup problems without starting any service. It is empty when the scene is ready.
Lifecycle
| Member | Description |
|---|---|
Initialize() | Validates the setup, binds the map roots and creates the SDK. Doesn’t access the network or camera. StartSession() calls it for you. |
StartSession() | Starts localization. Throws if the component is disabled, the app is in the background or the camera has no ARCameraManager. |
PauseSession() | Stops localization and hides map content. The AR Session keeps running. |
ResumeSession() | Continues after PauseSession(). |
ResetSession() | Clears the current localization, navigation and any pending transition, and localizes again if the session was running. It doesn’t reset the AR Session. |
Task ShutdownAsync() | Ends the session and releases its map roots and AR objects. Await it before you initialize again. |
IsInitialized, IsRunning | Whether the SDK exists, and whether it is localizing and navigating. |
The session pauses when the component is disabled or the app goes to the background, and resumes when it is back. A PauseSession() you call yourself stays in effect until you call ResumeSession(). Pause preserves the selected destination and a pending section transition; reset clears both. When a permission is granted again or tracking returns, an active session starts a fresh attempt without recreating your AR objects.
Events
Subscribe with +=. Events belong to the component, so subscriptions survive ShutdownAsync() and a new Initialize(). They are raised on the main thread, and a handler that throws is logged without stopping the other handlers.
session.StateChanged += state => statusLabel.text = state.Vps.Kind.ToString();
session.Localized += sectionId => Debug.Log("Localized in " + sectionId);
session.NavigationArrived += destination => Debug.Log("Arrived at " + destination.DisplayName);
session.Failed += error => Debug.LogWarning(error.Code + ": " + error.RecoverySuggestion);| Event | UnityEvent in the Events foldout | When |
|---|---|---|
StateChanged | On State Changed | State changes |
GuidanceChanged | — | Guidance changes |
Localized | On Localized | The device localizes in a section; the argument is the section ID |
Failed | On Failed | A new error is reported |
NavigationStarted | On Navigation Started | A route starts |
NavigationArrived | On Navigation Arrived | The player reaches the final destination |
NavigationStopped | On Navigation Stopped | Navigation stops |
From code, the UnityEvents are session.OnStateChanged, session.OnLocalized and so on.
State
session.State is an immutable GraffityARState snapshot. Before initialization and after shutdown it is idle, with no error.
| Property | Type | Description |
|---|---|---|
Vps | GraffityARVpsState | Localization status (see below) |
IsSceneReady | bool | The session has an active SDK. Use Vps and session.SceneBinding to check localization and map-root alignment. |
Navigation | GraffityARNavigationState? | Current route guidance, or null when not navigating |
LastError | GraffityARCloudError | The latest error, or null |
State.Vps.Kind is a GraffityARVpsStateKind:
| Kind | Meaning |
|---|---|
Idle | Not localizing |
AwaitingInitial | Waiting for the first usable view, for example while the player levels the phone |
Guiding | Localizing. Progress goes from 0 to 1. |
Localized | Localized. SectionId is the detected section. |
Failed | Localization failed. Error describes why. |
Localization guidance
During active localization, session.Guidance (and the GuidanceChanged event) tells you what to ask the player to do:
Phase | Show the player |
|---|---|
AwaitingInitial | “Hold your phone upright and level” |
Guiding | “Point the camera at the marker” |
WaitingForReply | “Hold still…” while VPS processes the view |
Failed | An error or retry prompt |
Idle | Nothing |
When Guidance.HasTarget is true, session.TryGetGuidanceTargetPose(out Pose pose) returns the camera pose the player should reach, in world space. To show a marker the player should aim at:
if (session.TryGetGuidanceTargetPose(out var target))
{
marker.transform.position = target.position + target.forward * 1.5f; // aim point in front of the target
marker.SetActive(true);
}
else
{
marker.SetActive(false);
}WaitingForReply follows each captured view. A later Guiding target can be a new view requested by VPS, so a changed target doesn’t mean the previous view was missed. A capture confirmation and a view counter help players through successive views. For a screen-space marker, project with the AR camera (for example WorldToViewportPoint) so portrait orientation is respected; a world marker alone can be outside the camera view.
The Host integration sample includes a complete guidance view, ActiveLocGuidanceView, and an overlay, VPSOverlayController, with English and Thai text.
Errors
State.LastError and the Failed event report a GraffityARCloudError. Its Code is a GraffityARCloudErrorCode that you can switch on, and RecoverySuggestion says what to do.
Code | Cause | Does the SDK retry by itself? |
|---|---|---|
InvalidAccessToken | Token rejected or malformed; a temporary token has expired, or a newer permanent token replaced it | No. The session shuts down; set a valid token and initialize again |
LocationNotAuthorized | Location denied and no InitialLocation | Resumes when location becomes available |
CameraNotAuthorized | Camera denied | Resumes when access is granted |
UnsupportedDevice | No AR world tracking | No |
TrackingUnavailable | Tracking lost longer than the tracking timeout | Resumes when tracking returns |
CaptureUnavailable | Camera frames could not be processed | Yes, with Auto Retry Localization on; otherwise call ResetSession() |
VpsUnavailable | Localization could not run | A failed start is not retried; call ResetSession() |
VpsAllAttemptsFailed | No map matched the view | Yes, with Auto Retry Localization on |
LocalizationUnavailable | Localization credentials unavailable | Yes, with Auto Retry Localization on |
NetworkUnavailable | No connection | During localization yes, with Auto Retry Localization on; a navigation request is not retried |
NavigationGraphUnavailable | Unknown POI or missing navigation data | No |
NavigationRouteUnavailable | No route between the sections. Destination and FromSection are set. | No |
ServerError | Server error. StatusCode is set. | No |
Cancelled | Pause, reset, shutdown or a newer request | Not needed |
Editor simulation
In Editor Play Mode the session simulates localization, and its simulation members (IsSimulated, SimulateLocalization, StartSimulatedWalk and others) let your Play Mode tests drive it. See Test in the Editor.
Analytics and diagnostics
The SDK records session, localization and navigation events. Built-in delivery follows your project’s SDK settings and the optional Analytics project key in Project Settings > Graffity AR Cloud. To turn built-in delivery off, set AnalyticsSampleRate = 0 in your configuration. A LogClient you supply receives the records on a background thread, even at a sample rate of 0, so it must be thread-safe.
To route SDK diagnostics to your own logger, implement IGraffityARDiagnosticLogger and pass Diagnostics = GraffityARDiagnostics.Custom(logger, GraffityARDiagnosticLevel.Info) in your configuration. GraffityARDiagnostics.Disabled silences them. Diagnostics never include tokens or camera images.
The SDK version is available at runtime as GraffityARCloudSession.SdkVersion.