Subscribing to ARDK Events
Get notified when AR and networking events relevant to your experience occur.
Overview
The core classes of ARDK (ARSession, MultipeerNetworking, and ARNetworking) all use a delegate model to signal to other systems when certain AR or networking events have occurred. This article describes how to subscribe to those events and some common use patterns.
Subscribing Synchronously
When constructing an instance of one of the ARSession, MultipeerNetworking, or ARNetworking classes, that instance can be used right away to subscribe to events.
void InitializeARSession() { var arSession = ARSessionFactory.Create(); arSession.Ran += OnSessionRan; } void OnSessionRan(ARSessionRanArgs args) { // Do something }
The same flow of constructing an instance using its class factory and then subscribing to events on that class can be applied to the MultipeerNetworking and ARNetworking systems.
Subscribing Asynchronously
Sometimes a core ARDK object will be created and managed in one class, but a reference to the object is needed in a different class. To avoid reference passing (and thereby introducing a potentially unneeded dependency between the two classes), you can subscribe to the event a factory raises when an instance is constructed.
void ListenForARSession() { ARSessionFactory.SessionInitialized += OnSessionInitialized; } void OnSessionInitialized(AnyARSessionInitializedArgs args) { args.Session.Ran += OnSessionRan; }
Events such as the two in the snippet above, as well as others like IMultipeerNetworking.Connected, will invoke delegates that subscribe after the event has already “happened.” For example, if ListenForARSession
gets called after an ARSession has already been initialized, OnSessionInitialized
will get invoked immediately.
Unsubscribing
To prevent null reference errors and memory leaks, remember to unsubscribe delegates when the publisher object (e.g. an ARSession) outlives the subscriber. If you are planning on switching scenes and/or creating new top level ARDK objects, do not subscribe with anonymous methods, and unsubscribe properly upon destruction.