Meta XR Core SDKの多くの操作は非同期です。SceneとSpatial Anchorsに関連するものは特にそうです。例えば、空間アンカーを保存するには、数フレームがかかる場合があります。非同期操作は将来いつか結果を生み出します。フレームワークによっては、これは未来と約束と呼ばれています。
async void OnButtonPress() {
// Inform user the operation is beginning
_ui.SetPendingIconEnabled(true);
// Initiate the operation and await the result
// (may take multiple frames)
var result = await _anchor.SaveAsync();
// Operation done; update UI
_ui.SetPendingIconEnabled(false);
// Process the result
if (result) {
// do something
} else {
// inform user
}
}
void SaveAnchor(OVRSpatialAnchor anchor) {
// Inform user the operation is beginning
_ui.SetPendingIconEnabled(true);
// Save and await the result (may take multiple frames)
anchor.SaveAsync().ContinueWith(OnSaveComplete);
}
void OnSaveComplete(bool success) {
_ui.SetPendingIconEnabled(false);
Debug.Log($"SaveAnchor completed with result {success}");
}
注:コールバックを提供したタスクをawaitしてはいけません。
以下の行為は認められていません。
async void OnButtonPress() {
var task = _anchor.SaveAsync();
task.ContinueWith(OnSave);
await task; // error; throws InvalidOperationException because
// the task is already being used with ContinueWith
}
void SaveAnchor(OVRSpatialAnchor anchor) {
// Inform user the operation is beginning
_ui.SetPendingIconEnabled(true);
// Provide a delegate and capture a reference to the anchor being saved
anchor.SaveAsync().ContinueWith(OnSaveComplete, anchor);
}
void OnSaveComplete(bool success, OVRSpatialAnchor anchor) {
_ui.SetPendingIconEnabled(false);
Debug.Log($"SaveAnchor {anchor.Uuid} completed with result {success}");
}