Skip to Content

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

FieldDescription
AR Session / XR OriginYour AR Foundation objects. Assigned automatically when the scene has exactly one of each. The XR Origin’s camera needs an ARCameraManager.
Map RootsThe GraffityARMapRoot of each section in this scene. The point-cloud browser and GameObject > XR > Graffity Map Root add roots for you.
Start On EnableStart localizing when the component is enabled. Off by default.
Navigation RendererOptional route arrow renderer. See Navigation.
Auto Retry LocalizationRetry failed localization automatically with backoff. On by default.
Advanced › Connection Timeout SecondsFirst reply and settings fallback deadline; default 15 seconds.
Advanced › Response Timeout SecondsEach later localization reply deadline; default 60 seconds.
Advanced › Tracking Timeout SecondsLongest tracking loss before TrackingUnavailable; default 30 seconds.
Advanced › Maximum Consecutive Frame FailuresFailed captures before an attempt fails; default 3.
EventsUnityEvents 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

MemberDescription
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, IsRunningWhether 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);
EventUnityEvent in the Events foldoutWhen
StateChangedOn State ChangedState changes
GuidanceChanged—Guidance changes
LocalizedOn LocalizedThe device localizes in a section; the argument is the section ID
FailedOn FailedA new error is reported
NavigationStartedOn Navigation StartedA route starts
NavigationArrivedOn Navigation ArrivedThe player reaches the final destination
NavigationStoppedOn Navigation StoppedNavigation 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.

PropertyTypeDescription
VpsGraffityARVpsStateLocalization status (see below)
IsSceneReadyboolThe session has an active SDK. Use Vps and session.SceneBinding to check localization and map-root alignment.
NavigationGraffityARNavigationState?Current route guidance, or null when not navigating
LastErrorGraffityARCloudErrorThe latest error, or null

State.Vps.Kind is a GraffityARVpsStateKind:

KindMeaning
IdleNot localizing
AwaitingInitialWaiting for the first usable view, for example while the player levels the phone
GuidingLocalizing. Progress goes from 0 to 1.
LocalizedLocalized. SectionId is the detected section.
FailedLocalization failed. Error describes why.

Localization guidance

During active localization, session.Guidance (and the GuidanceChanged event) tells you what to ask the player to do:

PhaseShow the player
AwaitingInitial“Hold your phone upright and level”
Guiding“Point the camera at the marker”
WaitingForReply“Hold still…” while VPS processes the view
FailedAn error or retry prompt
IdleNothing

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.

CodeCauseDoes the SDK retry by itself?
InvalidAccessTokenToken rejected or malformed; a temporary token has expired, or a newer permanent token replaced itNo. The session shuts down; set a valid token and initialize again
LocationNotAuthorizedLocation denied and no InitialLocationResumes when location becomes available
CameraNotAuthorizedCamera deniedResumes when access is granted
UnsupportedDeviceNo AR world trackingNo
TrackingUnavailableTracking lost longer than the tracking timeoutResumes when tracking returns
CaptureUnavailableCamera frames could not be processedYes, with Auto Retry Localization on; otherwise call ResetSession()
VpsUnavailableLocalization could not runA failed start is not retried; call ResetSession()
VpsAllAttemptsFailedNo map matched the viewYes, with Auto Retry Localization on
LocalizationUnavailableLocalization credentials unavailableYes, with Auto Retry Localization on
NetworkUnavailableNo connectionDuring localization yes, with Auto Retry Localization on; a navigation request is not retried
NavigationGraphUnavailableUnknown POI or missing navigation dataNo
NavigationRouteUnavailableNo route between the sections. Destination and FromSection are set.No
ServerErrorServer error. StatusCode is set.No
CancelledPause, reset, shutdown or a newer requestNot 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.