Skip to main content
Version: 2.3.1

Handle the Situation of Failed Anchor Saving

The following three scripts are included in the NRSDK. However, to implement the "Halloween Treasure Hunt" tutorial, we need to make some modifications. Specifically, to handle the potential confusion caused by the possible failure of anchor saving, we will obtain callbacks for both successful and failed saves, and provide users with appropriate prompts. The modifications made to these scripts to achieve this are provided below. Please copy them directly and replace the original script content.

/****************************************************************************
* Copyright 2019 XREAL Techonology Limited. All rights reserved.
*
* This file is part of NRSDK.
*
* https://www.xreal.com/
*
*****************************************************************************/

namespace NRKernal.Persistence
{
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// <summary> An anchor item. </summary>
public class AnchorItem : MonoBehaviour, IPointerClickHandler
{

public ScoreManager scoreManager;

public GameObject failedPanel; // Private variables are used to store references to panels.

public Button saveButton;

/// <summary> The key. </summary>
public string key;
/// <summary> The on anchor item click. </summary>
public Action<string, GameObject> OnAnchorItemClick;
/// <summary> The anchor panel. </summary>
[SerializeField]
private GameObject canvas;
[SerializeField]
private Text anchorUUID;

private NRWorldAnchor m_NRWorldAnchor;
private Material m_Material;


void Start()
{
if (TryGetComponent(out m_NRWorldAnchor))
{
if (canvas != null)
canvas.SetActive(true);
if (anchorUUID != null)
anchorUUID.text = m_NRWorldAnchor.UUID;
m_Material = GetComponentInChildren<Renderer>()?.material;
if (m_Material != null)
{
m_NRWorldAnchor.OnTrackingChanged += (NRWorldAnchor worldAnchor, TrackingState state) =>
{
switch (state)
{
case TrackingState.Tracking:
// m_Material.color = Color.green;
UnityEngine.Debug.Log("Successfully found the treasure");
scoreManager.AddScore(1);
break;
case TrackingState.Paused:
m_Material.color = Color.white;
break;
case TrackingState.Stopped:
m_Material.color = Color.red;
break;
}
};
}
}
}

public void Save()
{
if (m_NRWorldAnchor != null)
{

m_NRWorldAnchor.SaveAnchor(success =>
{
if (success)
{
Debug.Log("Anchor saved successfully!");
saveButton.image.color = Color.green;
}
else
{
Debug.LogError("Failed to save anchor!");
failedPanel.SetActive(true);
saveButton.image.color = Color.red;
}
});

}

}

public void Erase()
{
if (m_NRWorldAnchor != null)
m_NRWorldAnchor.EraseAnchor();
}

public void Destory()
{
if (m_NRWorldAnchor != null)
m_NRWorldAnchor.DestroyAnchor();
}

public void OnPointerClick(PointerEventData eventData)
{
OnAnchorItemClick?.Invoke(key, gameObject);
}

}
}